Python 2.7 Tkinter绑定:循环重复自身(Python)
我正在尝试编写一个游戏,其中一个盒子在屏幕上根据箭头键移动,当我按下“空格”按钮时,它将暂停 出于某种原因,当我按下空格键时,它会返回到“NewGame()”循环,就好像什么都没发生一样。为什么会这样Python 2.7 Tkinter绑定:循环重复自身(Python),python-2.7,tkinter,event-binding,Python 2.7,Tkinter,Event Binding,我正在尝试编写一个游戏,其中一个盒子在屏幕上根据箭头键移动,当我按下“空格”按钮时,它将暂停 出于某种原因,当我按下空格键时,它会返回到“NewGame()”循环,就好像什么都没发生一样。为什么会这样 from Tkinter import * HEIGHT = 400 WIDTH = 300 cHEIGHT=HEIGHT-100 cWIDTH=WIDTH TOPLEFT=3 BUTTOMRIGHT=13 RECTANGLE_SIDE=BUTTOMRIGHT-TOPLEFT def NewG
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()
从Tkinter导入*
高度=400
宽度=300
切特=高度-100
cWIDTH=宽度
左上角=3
按钮右=13
矩形=按钮右上左
def NewGame():
def键(事件):
尽管如此:
(x1,y1,x2,y2)=画布坐标(头部)
如果event.keysym=='Right':
画布移动(头部,1,0)
root.update()
如果x1>=cWIDTH:
canvas.move(head,-cWIDTH,0)
elif event.keysym=='Left':
画布移动(头部-1,0)
root.update()
如果x2您需要删除while
循环
您将while循环设置为在True
上运行,这当然意味着它将无限期运行,除非您中断循环。从循环中断的唯一实例是当event.keysym==“space”
时
因此,如果event.keysym
等于space
以外的任何值,while循环将无限循环
def Key(event):
(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':
pass
def键(事件):
(x1,y1,x2,y2)=画布坐标(头部)
如果event.keysym=='Right':
画布移动(头部,1,0)
root.update()
如果x1>=cWIDTH:
canvas.move(head,-cWIDTH,0)
elif event.keysym=='Left':
画布移动(头部-1,0)
root.update()
如果x2您希望在遇到事件之前一直运行该循环。keysym=='space'
条件
您可以尝试在while
循环中使用该条件,而不是在True
上运行循环并等待按下空格
来中断循环,只要尚未按下空格
,就让循环运行
详情如下:
def键(事件):
while event.keysym!='空格':
(x1,y1,x2,y2)=画布坐标(头部)
如果event.keysym=='Right':
画布移动(头部,1,0)
root.update()
如果x1>=cWIDTH:
canvas.move(head,-cWIDTH,0)
elif event.keysym=='Left':
画布移动(头部-1,0)
root.update()
如果这没有帮助,因为我想按一下箭头键,使其移动,直到按下另一个键。这就是为什么我使用而True:
循环。当我运行程序时,当按下“空格”时,它不会退出while循环。