[英]How to capture the enter key in Python without Tkinter
如果按下回車鍵,我需要使程序從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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.