如果按下回车键,我需要使程序从Python重新开始。我找到了这个问题和解决方案:如何检查回车键是否按python。但是,当我搜索event.keysym时,它似乎与Tkinter有关,但我认为我没有。
当我尝试使用解决方案时,出现错误:
Traceback (most recent call last):
File "/home/q/Desktop/PigsAndBulls.py", line 52, in <module>
if event.keysym == 'Return':
NameError: name 'event' is not defined
我是一位完全的新手,刚完成与Coursera的Severance博士的课程。
这是我写的玩猪和公牛的程序。一切都如我所愿。唯一的问题是,如果按下除“输入”按钮以外的任何其他键,则退出程序。
while True:
while True:
word= raw_input("Enter a four letter English word with no repeating letters: ")
print
if len(word) <> 4:
print "What part of 'four letter word' did you not understand? Try again."
print
continue
else: break
guesses = 0
while True:
correct = 0
position = 0
cnt = 0
result = 0
guess= raw_input("Enter a guess: ")
guesses = guesses+1
#print "guessses", guesses
for w in guess:
cnt = cnt+1
#print "cnt", cnt
position=0
for g in word:
position=position+1
#print "position", position
if g == w:
correct = correct+1
if position == cnt:
result = result+1
#print "result", result
print
print "Number correct:", correct
print "Number in the right position:", result
print
if correct<>4 and result<>4:
print "Give me another guess"
print
continue
elif correct == 4 and result == 4:
print
print "YOU WIN"
print
print "It took you", guesses, " guesses to get it right"
print
break
answer= raw_input("press ""enter"" to play again")
if event.keysym == 'Return':
continue
else:
exit
print
print
然后我想,也许我已经用字符串变量“ answer”替换了“ event”,但随后出现此错误:
Traceback (most recent call last):
File "/home/q/Desktop/PigsAndBulls.py", line 52, in <module>
if answer.keysym == 'Return':
AttributeError: 'str' object has no attribute 'keysym'
另外,如果我按其他任何键,它只会在空闲状态下打印,并且程序不会退出。
顺便说一句,我知道必须有一种使用列表或词典对此进行编程的更好方法,但这就是我所知道的全部方法。
按下enter
将导致长度为零的单词。使您的第一张支票。
但是,如果您想捕获单个按键,例如C中的getch(),则要复杂得多,例如https://stackoverflow.com/a/6599441/493161
另一个选择是捕获^ C(control-C):
try:
answer = raw_input('Control-C to exit, <ENTER> to play again: ')
if len(answer) > 0:
raise(ValueError('Unexpected input'))
else:
continue
except (KeyboardInterrupt, ValueError):
sys.exit(0)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句