我正在尝试创建一个画布,其中出现 100 个完全随机的矩形,但我得到的是空白画布和一个错误:
无效的命令名称“.!canvas”
我该如何解决这个问题?
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)
tk.mainloop()
是用于启动事件循环的命令,因此您在声明矩形位置的变量之前生成窗口。
将
tk.mainloop()
放在脚本末尾,它就可以正常运行,请参见下文:
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()