2

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)
2
  • I would also recommend updating your title to an actual question Commented Aug 4, 2017 at 15:26
  • It is because tkinter window closed but other processes related to it e.g. canvas.delete('ball') is still running. To avoid this, put try and except when calling animate() function. To avoid the error, import sys and do this whenever animate() is called: try: self.animate() except: sys.exit(1) Commented Jan 26, 2022 at 7:14

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

1 Comment

"tk.mainloop() is the command used to generate the tKinter master window" - that is a false statement. It doesn't create or generate any windows, it simply starts the event loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.