我正在尝试编写一个游戏,其中一个框根据箭头键在屏幕上移动,当我按下“空格”按钮时,它会暂停。
出于某种原因,当我按下空格键时,它会返回到“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()