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()

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

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

注意:您需要删除循环。您绝对不应该在GUI程序中创建无限的循环,并且您肯定不想创建每个迭代的框架 - 最终只会在一秒钟或两个中获得成千上万的帧呢

您已经有一个无限的循环运行,Mainloop。如果要进行动画,请使用after每几毫秒运行一个功能。例如,以下将导致每秒钟10秒钟移动10个像素。当然,您需要处理它从屏幕或反弹或其他任何情况下移动的情况。关键是,您编写一个绘制一个动画框架的函数,然后将该函数定期调用。

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

最新更新