Tkinter 中的 Keyup 处理程序?

Nir*_*uah 4 python keyboard tkinter

标题说明了一切。我可以调用 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()
Run Code Online (Sandbox Code Playgroud)

Bry*_*ley 5

您可以定义前缀为 的事件KeyRelease,例如<KeyRelease-a>。例如:

canvas.bind("<KeyRelease-a>", do_something)
Run Code Online (Sandbox Code Playgroud)

注意:您需要删除 while 循环。您永远不应该在 GUI 程序中创建无限循环,并且您绝对不希望每次迭代都创建一个帧 - 您最终会在一两秒内创建数千个帧!

您已经有一个正在运行的无限循环,即主循环。如果您想制作动画,请after每隔几毫秒运行一个函数。例如,以下代码将导致球每十分之一秒移动 10 个像素。当然,您需要处理它移出屏幕或弹跳或其他任何情况的情况。要点是,您编写一个绘制一帧动画的函数,然后定期调用该函数。

def animate():
    canvas.move("ball", 10, 0)
    canvas.after(100, animate)
Run Code Online (Sandbox Code Playgroud)