我可能对捕捉按键的工作原理有一个根本的误解。我已经设置了基本的按键和效果,但当我尝试在更大的脚本中执行相同的操作时,它没有效果。例如,第一个程序工作得很好。我按下空格键,窗口关闭。
import Tkinter as tk
class ExampleApp(tk.Tk):
def __init__(self):
def pressSpace(event):
self.destroy()
tk.Tk.__init__(self)
w, h = self.winfo_screenwidth(), self.winfo_screenheight()
self.geometry("%dx%d+0+0" % (w, h))
self.bind("<space>", pressSpace)
if __name__ == "__main__":
app = ExampleApp()
app.mainloop()
但当按下空格时,第二个按钮似乎没有任何作用。
#Program has been greatly simplified without affecting the outcome
import Tkinter as tk
class ExampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
# make program fullscreen
w, h = self.winfo_screenwidth(), self.winfo_screenheight()
self.geometry("%dx%d+0+0" % (w, h))
self.label = tk.Label(self)
self.label.pack()
self.remaining = 0
self.countdown(15)
def countdown(self, remaining = None):
paused = 0
def pressSpace(event):
if(paused == 0):
paused = 1
else:
paused = 0
#bind spacebar to pause the timer
self.bind(self, "<space>", pressSpace)
if remaining is not None:
self.remaining = remaining
if self.remaining <= 0:
#Time has expired. Players lose
self.label.configure(text="TIME!", fg='black', bg='brown')
else:
#There is still time on the clock. This cuts the time into readable chunks
self.label.configure(text= str(self.remaining) + ' - Paused = ' + str(paused))
if(paused == 0):
#Check if the timer is toggled to pause
self.remaining = self.remaining - 1
self.after(1000, self.countdown)
if __name__ == "__main__":
app = ExampleApp()
app.mainloop()
我不明白。程序在功能上似乎相似,所有内容都包含在同一个函数中,但变量“暂停”似乎根本没有改变,计时器也不会停止。
我很害怕。我是否偏离了正道?