Skip to content Skip to sidebar Skip to footer

Invalid Command Name ".!canvas"

I'm attempting to create a canvas with 100 completely random rectangles appearing, but what I get is a blank canvas and an error: invalid command name '.!canvas' How do i fix this?

Solution 1:

tk.mainloop() is the command used to start the event loop, as such you're generating the window before you've declared the variables for the rectangle positions.

Place tk.mainloop() at the end of your script and it runs fine, see below:

from tkinter import *
import random
tk = Tk()
canvas = Canvas(tk, width=400, height=400)
canvas.pack()

defrndm_rect(width, height):
    x1 = (random.randrange(width))
    y1 = (random.randrange(height))
    x2 = x1 + (random.randrange(width))
    y2 = y1 + (random.randrange(width))
    canvas.create_rectangle(x1, y1, x2, y2)

rndm_rect(400, 400)


for x inrange(0, 100):
    rndm_rect(400, 400)

tk.mainloop()

Post a Comment for "Invalid Command Name ".!canvas""