python - tkinter 中的画布无法通过按键功能更改
问题描述
我正在学习 python tkinter。我想写一个这样的功能,当我按下“a”然后球停止落下。为什么我按键盘,功能可以运行,但它不改变画布?
tk = tkinter.Tk()
canvas = tkinter.Canvas(tk,width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()
circle=canvas.create_oval(50,50,80,80, fill="yellow")
dir = True
def stop(event):
dir = False
def move_func():
canvas.move(circle, 0, 1)
def key_stop():
tk.bind_all("a",stop)
while dir:
move_func()
key_stop()
canvas.update_idletasks()
canvas.update()
tk.mainloop()
我试图在停止功能中打印一些东西,效果很好。但是如果我想在画布上添加一个椭圆或改变一些东西,它就行不通了。谢谢。
解决方案
这是因为dir
instop()
是一个局部变量,而不是全局变量。您需要在global dir
里面添加stop()
:
def stop():
global dir
dir = False
但是,不建议在 tkinter 应用程序中使用 while 循环。改用after()
:
import tkinter
tk = tkinter.Tk()
canvas = tkinter.Canvas(tk,width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()
circle = canvas.create_oval(50, 50, 80, 80, fill="yellow")
dir = True
def stop(event):
global dir
dir = False
def move_func():
if dir:
canvas.move(circle, 0, 1)
tk.after(5, move_func)
tk.bind_all("a", stop)
move_func() # start moving the circle
tk.mainloop()
推荐阅读
- git - 修复从提交到提交的 git 断开链接
- javascript - 如何在 google app scipts 中加速这个循环?
- c# - 如何使用 DataAnnotations & Regex - c# - ASP.NET Core
- julia - 为什么 Julia (DifferentialEquations.jl) JumpProblem 在以后停止跳跃?
- angular - Angular中大项目列表的下拉菜单
- javascript - 从firebase实时数据库渲染FlatList React Native(expo cli)中的数据?
- python - python sympy - 如何处理表达式以保护它们免受特定评估
- c++ - 如何将 c++11 中的这个 stoi 使用转换为 atoi?
- git - 带有隐式变基的 git force pull
- tiff - 为 EXIF 找到 TIFF 标头中的字节顺序 0x49 0x01