我试图在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()
虽然这不是一个好的实践,但如果将行
global square
添加到makeShape()
,它将按预期运行这是因为如果第一次在块内指定名称,则父块或同级块将看不到该名称
有一些替代方案,考虑到可读性和实用性更好,但我的建议是解决您问题的最快方法
这是因为
square
是makeShape()
内部的局部变量,因此无法在函数外部访问它您可以在
create_polygon()
中使用tags
选项。如果要在单击正方形时移动它,deleteShape()
根本不需要。仅仅使用makeShape()
就足够了:相关问题 更多 >
编程相关推荐