Tkinter中的Keyup处理器?

4 投票
1 回答
3947 浏览
提问于 2025-04-17 21:23

标题已经说明了一切。我想知道在Tkinter中有没有什么方法可以让我监控特定的按键释放,并把它和一个函数连接起来?我想用这个来结束一个计时器,这个计时器是我用来移动我的物品的。下面是代码:

from Tkinter import *

master = Tk()
master.wm_title("Ball movement")

width = 1000
height = 600
circle = [width / 2, height / 2, width / 2 + 50, height / 2 + 50]

canvas = Canvas(master, width = width, height = height, bg = "White")
canvas.pack()
canvas.create_oval(circle, tag = "ball", fill = "Red")

while True:
    canvas.update()
    def move_left(key):
        #This is where my timer will go for movement
        canvas.move("ball", -10, 0)
        canvas.update()
    def move_right(key):
        #This is where my other timer will go
        canvas.move("ball", 10, 0)
        canvas.update()
    frame = Frame(master, width=100, height=100)
    frame.bind("<Right>", move_right)
    frame.bind("<Left>", move_left)
    frame.focus_set()
    frame.pack()

mainloop()

1 个回答

5

你可以定义一些以 KeyRelease 开头的事件,比如 <KeyRelease-a>。举个例子:

canvas.bind("<KeyRelease-a>", do_something)

注意:你需要去掉你的 while 循环。在图形用户界面(GUI)程序里,绝对不要创建无限循环。而且,你肯定不想在每次循环中都创建一个新的窗口——这样的话,没过多久就会出现成千上万个窗口!

其实你已经有一个无限循环在运行了,那就是 mainloop。如果你想做动画,可以用 after 来每隔几毫秒运行一个函数。比如,下面的代码会让一个球每0.1秒移动10个像素。当然,你还需要处理球移动出屏幕、反弹等情况。关键是,你需要写一个函数来绘制动画的每一帧,然后让这个函数定期被调用。

def animate():
    canvas.move("ball", 10, 0)
    canvas.after(100, animate)

撰写回答