我试图编写一个游戏,其中一个框在屏幕上根据箭头键移动,当我按下'space'按钮时它会暂停。Tkinter绑定:循环重复自己(Python)
出于某种原因,当我按下空格按钮时,它会返回到'NewGame()'循环,就好像什么都没发生一样。这是为什么发生?
from Tkinter import *
HEIGHT = 400
WIDTH = 300
cHEIGHT=HEIGHT-100
cWIDTH=WIDTH
TOPLEFT=3
BUTTOMRIGHT=13
RECTANGLE_SIDE=BUTTOMRIGHT-TOPLEFT
def NewGame():
def Key(event):
while True:
(x1,y1,x2,y2)=canvas.coords(head)
if event.keysym =='Right':
canvas.move(head,1,0)
root.update()
if x1>=cWIDTH:
canvas.move(head, -cWIDTH,0)
elif event.keysym=='Left':
canvas.move(head,-1,0)
root.update()
if x2<=0:
canvas.move(head, cWIDTH,0)
elif event.keysym=='Up':
canvas.move(head,0,-1)
root.update()
if y2<=0:
canvas.move(head, 0,cHEIGHT)
elif event.keysym=='Down':
canvas.move(head,0,1)
root.update()
if y1>=cHEIGHT:
canvas.move(head, 0,-cHEIGHT)
elif event.keysym=='space':
break
canvas.delete("all")
head=canvas.create_rectangle(TOPLEFT,TOPLEFT,BUTTOMRIGHT,BUTTOMRIGHT)
root.bind('<Key>', Key)
root = Tk()
root.geometry(('%dx%d')%(HEIGHT,WIDTH))
b1 = Button(root, text = 'New Game', command=NewGame)
b1.pack()
canvas=Canvas(root, height = cHEIGHT, width = cWIDTH)
canvas.pack()
root.mainloop()
这没有帮助,因为我要上箭头键一个按,使之移动,直到一个不同的键被按下。这就是我使用'while True:'循环的原因。当我运行我的程序时,当'space'被按下时它不会退出while循环。 –