我是 Python 新手,我正在尝试编写一个随时接受用户输入的代码(以按键的形式),并且根据用户按下某些键时的条件,条件会发生变化。这是我到目前为止所拥有的:
import Tkinter as tk
import time
timeout = time.time() + 30
def keypress(event):
global alive
if event.keysym == 'Escape':
alive = False
x = event.char
if x == "l":
print("hello")
elif x == "s":
print("no")
elif x == "r":
print("maybe")
elif x == "g":
print("bye")
else:
print(x)
root = tk.Tk()
print("Press a key (Escape key to exit):")
root.bind_all('<Key>', keypress)
global alive
alive = True
while alive:
start = time.time()
if time.time() > timeout:
print "Game Over"
break
# do stuff here, this is in my main loop where I am trying to put the 'if' statements
root.update()
此代码接受某些按键,并根据按键打印出相应的行。while 循环允许这种情况在“游戏结束”之前发生一段时间。我想要做的是使用按键作为输入在我的while循环中设置if语句。例如(类似的东西):
if x == 'l' and sound == True:
print "bla blabla"
sound == False
elif x == 'l' and sound == False:
print "blahblahblah"
sound == True
问题是我不断收到一条错误消息,上面写着“未定义 x”,或者类似的内容。请帮忙!另外,我正在使用Mac。