标题说明了一切。在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()发布于 2014-03-08 02:32:03
您可以定义以KeyRelease为前缀的事件,例如<KeyRelease-a>。例如:
canvas.bind("<KeyRelease-a>", do_something)注意:您需要删除while循环。您不应该在GUI程序中创建无限循环,而且您肯定不希望每次迭代都创建一个框架--您将在一两秒钟内得到数千个帧!
你已经有一个无限循环在运行,主循环。如果要执行动画,请使用after每隔几毫秒运行一次函数。例如,以下内容将导致一个球每10秒钟移动10像素。当然,你会想要处理的情况下,它移动离开屏幕或反弹或其他什么。重点是,编写一个绘制一个动画框架的函数,然后定期调用该函数。
def animate():
canvas.move("ball", 10, 0)
canvas.after(100, animate)https://stackoverflow.com/questions/22263879
复制相似问题