无效的命令名称“。!canvas”

时间:2017-08-04 13:23:39

标签: python-3.x tkinter tkinter-canvas

我正在尝试创建一个出现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)

1 个答案:

答案 0 :(得分:2)

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()