【发布时间】:2016-03-19 09:52:52
【问题描述】:
当我按下 UpArrow、DownArrow、LeftArrow 或 RightArrow 时,我正在模拟一个“下降”动作。我想它会移动,但是当我打开 Tkinter 时我没有得到任何回应。似乎在sleep() 时间和Tk.after() 时间都没有得到任何按键。我该如何解决这个问题?
这是我使用 Python-2.7 和 Tkinter 的代码。
from Tkinter import *
import msvcrt,time
root=Tk()
c=Canvas(root,height=900,width=700)
c.pack()
p0=(450,450)
p1=(460,460)
a1=c.create_oval(p0,p1,fill='red')
def foo():
if msvcrt.kbhit():
key=msvcrt.getch()
if key=='P':
c.move(a1,0,5)
a1.itemconfig(fill='yellow')
elif key=='H':
c.move(a1,0,-5)
a1.itemconfig(fill='blue')
elif key=='K':
c.move(a1,-5,0)
a1.itemconfig(fill='white')
elif key=='M':
c.move(a1,5,0)
a1.itemconfig(fill='green')
elif key =='\x1b':
root.exit()
c.after_cancel(m)
c.pack()
sleep(0.5)
#root.update()
foo()
else:
c.move(a1,0,2)
m=c.after(1000,foo)
#sleep(0.5)
#root.update()
c.pack()
foo()
root.mainloop()
【问题讨论】:
-
你为什么在 tkinter 程序中使用
msvcrt.getch()?无论如何,当程序处于休眠状态时,您没有识别任何键是正确的。这就是为什么你永远不应该在 GUI 程序的主线程中调用sleep。 -
对不起,我是一个初学者,不明白...我设法在 Tkinter 中使用 msvcrt.getch() 而不睡觉,它响应了。这就是我尝试制作俄罗斯方块程序的原因.谢谢你的回答:)
标签: python python-2.7 tkinter