【问题标题】:Keyup handler in Tkinter?Tkinter 中的键盘处理程序?
【发布时间】:2014-04-11 09:56:31
【问题描述】:

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

【问题讨论】:

    标签: python keyboard tkinter


    【解决方案1】:

    您可以定义以KeyRelease 为前缀的事件,例如&lt;KeyRelease-a&gt;。例如:

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

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

    你已经有一个无限循环在运行,主循环。如果你想做动画,使用after 每隔几毫秒运行一个函数。例如,以下将导致球每 10 秒移动 10 个像素。当然,您需要处理它移出屏幕或反弹或其他情况的情况。关键是,您编写一个绘制一帧动画的函数,然后定期调用该函数。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-03
      • 1970-01-01
      • 1970-01-01
      • 2010-11-27
      • 2019-05-01
      • 2016-05-15
      • 2014-05-09
      相关资源
      最近更新 更多