0

I am writing a program in which whenever a user press the button the circle should draw on the window. But I don't know why this button is not working properly.

from tkinter import *
root = Tk()

root.geometry("500x500")
myCanvas = Canvas(root)
myCanvas.pack()

def create_circle(x, y, r, canvasName):
    x0 = x - r
    y0 = y - r
    x1 = x + r
    y1 = y + r
    return canvasName.create_oval(x0, y0, x1, y1)


buttonCal = Button(myCanvas, text="Submit", 
    command=lambda: create_circle(200, 200, 80, myCanvas))
buttonCal.pack(padx = 5, pady = 5)

root.mainloop()
  • 1
    You should not use `pack()` to put the button in the canvas. Or you should make the button the child of `root` instead of `myCanvas`. – acw1668 Aug 19 '20 at 10:33
  • 1
    You put your button in the same canvas with your oval – tibi Aug 19 '20 at 10:42

2 Answers2

1

You put the button and oval in the same canvas. So the button overlap the oval.

from tkinter import *
root = Tk()

root.geometry("500x500")


def create_circle(x, y, r, canvasName):
    x0 = x - r
    y0 = y - r
    x1 = x + r
    y1 = y + r
    return canvasName.create_oval(x0, y0, x1, y1)

button_canvas = Canvas(root) # put the button in button_canvas or you can put
                             # it in the root
button_canvas.pack()

oval_canvas = Canvas(root, width=300, height=300)
oval_canvas.pack()

buttonCal = Button(button_canvas, text="Submit", command=lambda: create_circle(200, 200, 80, myCanvas))
buttonCal.pack()

root.mainloop()
tibi
  • 186
  • 3
  • 11
-1

Replacing buttonCal.pack(padx = 5, pady = 5) with buttonCal.place(relx=0.5, rely=0, anchor=N) does the trick. It specifies coordinates of your button in a same way as oval is being created. By contrast, buttonCal.pack() 'occupies' a box model which is not consistent with coordinate model of a circle placed.

There is more information about this problem

mathfux
  • 5,759
  • 1
  • 14
  • 34
  • While the core of the answer is correct (the button is inside the canvas) the description is not. It's not that `pack` isn't consistent with the coordinate model, but rather that `pack` causes the canvas to shrink to the point where the circle isn't visible. The circle is actually there, it's just not visible. Also, the linked question is not at all related to this problem. – Bryan Oakley Aug 19 '20 at 14:43