pythontkintergeometryshapeszelle-graphics

Generate and place random points inside a circle


I have a task where I am supposed to create a circle and plot some random points inside it. I am new to Python and Python libraries. I need some suggestions about different software or packages that might help me with my task.

I have seen some YouTube videos, but they were not relevant to my topic. This is the code I saw in a tutorial to create a circle:

from graphics import *

def main():
        win = GraphWin("my window",500,500)
        pt = Point(250,250)
        win.setBackground(color_rgb(255,255,255))
        cir = Circle(pt,50)
        cir.draw(win)
        win.getMouse()
        win.close()
main()

Can I continue with this graphics class to complete my task? If not, then please suggest a good library or s/w.


Solution

  • 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 tk
    
    
    def distance_to_center(x, y):
        return ((x-200)**2 + (y-200)**2)**0.5
    
    def 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()