首页 > 解决方案 > 如何在 tkinter 中删除多边形?

问题描述

我正在尝试在 Tkinter 中制作一个基本游戏,其中包括按下开始按钮并显示一个正在工作的形状,然后当您单击该形状时,它会被删除并移动到另一个随机位置。

NameError: name 'square' is not defined当我尝试运行它时,我得到了。

root=Tk()
frame=Frame(root)
can = Canvas(root, width=400, height=400)
can.pack(side=TOP)

def makeShape():
    xpos = random.randint(1, 400)
    ypos = random.randint(1, 400)
    square=can.create_polygon(xpos, ypos, xpos + 40, ypos, xpos + 40, ypos + 40, 
                              xpos, ypos + 40, fill="blue")
    can.tag_bind(square,"<Button-1>",deleteShape)

def deleteShape(event):
    can.delete(square)

but1 = Button(frame, text="Start", command=makeShape)
but1.grid(row=1, column=2)

frame.pack(side=BOTTOM)
root.mainloop()

标签: pythontkinter

解决方案


虽然这不是一个好习惯,但如果您向其中添加行global squaremakeShape()它将按预期运行。

这是因为如果名称是第一次在块内分配,则父块或兄弟块将看不到它。

有替代方案,被认为更好的可读性和更实用,但我的建议是最快解决您的问题。


推荐阅读