Generate and place random points inside a circle Generate and place random points inside a circle tkinter tkinter

Generate and place random points inside a circle


You can use tkinter, and a canvas widget.

The following example traces a circle centered at 200, 200 on the canvas. Upon a mouse click, the distance from the center is calculated, and if it is smaller than the radius, a point is drawn on the canvas.

import tkinter as tkdef distance_to_center(x, y):    return ((x-200)**2 + (y-200)**2)**0.5def place_point(e):    if distance_to_center(e.x, e.y) < 100:        canvas.create_oval(e.x-2, e.y-2, e.x+2, e.y+2)root = tk.Tk()canvas = tk.Canvas(root, width=400, height=400)canvas.create_oval(100, 100, 300, 300)canvas.pack()canvas.bind('<1>', place_point)root.mainloop()


Here's my reimplementation of @ReblochonMasque's tkinter example (+1) using turtle graphics:

import turtleLARGE_RADIUS, SMALL_DIAMETER = 100, 4def place_point(x, y):    turtle.goto(x, y)    if turtle.distance(0, 0) < LARGE_RADIUS:        turtle.dot(SMALL_DIAMETER)turtle.setup(width=400, height=400)turtle.hideturtle()turtle.speed('fastest')turtle.penup()turtle.sety(-LARGE_RADIUS)  # center circle at (0, 0)turtle.pendown()turtle.circle(LARGE_RADIUS)turtle.penup()turtle.onscreenclick(place_point)turtle.mainloop()

Although, like Zelle graphics.py, turtle graphics is implemented atop tkinter, it uses a different coordinate system. In terms of complexity and capability:

Zelle graphics.py < turtle < tkinter

If you find tkinter too complex for your needs, and Zelle graphics.py insufficient, consider turtle graphics, which, like tkinter, comes with Python.

Can I continue with this graphics class to complete my task?

Possibly. Here's an example next step from where you left off:

from graphics import *WIDTH, HEIGHT = 500, 500LARGE_RADIUS, SMALL_RADIUS = 50, 2CENTER = Point(WIDTH/2, HEIGHT/2)def distance_to_center(point):    return ((point.getX() - CENTER.getX())**2 + (point.getY()- CENTER.getY())**2) ** 0.5win = GraphWin("My Window", WIDTH, HEIGHT)circle = Circle(CENTER, LARGE_RADIUS)circle.draw(win)while True:    point = win.getMouse()    if distance_to_center(point) < LARGE_RADIUS:        dot = Circle(point, SMALL_RADIUS)        dot.draw(win)