Search code examples
pythonpython-3.xtkintertkinter-canvas

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?

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

def rndm_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 in range(0, 100):
    rndm_rect(400, 400)

Solution

  • 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()
    
    def rndm_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 in range(0, 100):
        rndm_rect(400, 400)
    
    tk.mainloop()