当我按上箭头、下箭头、左箭头或右箭头时,我正在模拟“下降”动作。我认为它会移动,但是当我打开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()
msvcrt.getch()
?无论如何,您是正确的,当程序处于睡眠状态时不会识别任何键。这就是为什么您永远不应该在GUI程序的主线程中调用sleep
的原因。 - Bryan Oakley