python - 如何在 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()
解决方案
虽然这不是一个好习惯,但如果您向其中添加行global square
,makeShape()
它将按预期运行。
这是因为如果名称是第一次在块内分配,则父块或兄弟块将看不到它。
有替代方案,被认为更好的可读性和更实用,但我的建议是最快解决您的问题。
推荐阅读
- mysql - 如果密钥存在如何更新,否则插入
- ecmascript-6 - 破坏 Parse.Object 实例
- java - Android 许可证状态未知。尝试重新安装或更新您的 Android SDK 管理器
- spring-boot - 在 Spring Boot 2 中,如何自动生成数据库并将模式生成命令记录到文件中?
- node.js - 构建成功时无法将我的应用程序部署到 Heroku 空白页面和控制台错误?
- r - 在 R 中操作数据帧、标记错误并返回新数据集
- swift - 如何在初始化后自动异步设置现有结构的新属性?
- javascript - 如何使用来自 React Router 和 Redux 的 Props 从服务器获取数据
- mongoose - 在执行查询之前验证
- javascript - 如何将选定的选项值添加到 HTML 表单中的 jQuery 多选?