首页 > 解决方案 > 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()

我试图在停止功能中打印一些东西,效果很好。但是如果我想在画布上添加一个椭圆或改变一些东西,它就行不通了。谢谢。

标签: pythonpython-3.xtkinter

解决方案


这是因为dirinstop()是一个局部变量,而不是全局变量。您需要在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()

推荐阅读