如何在没有Tkinter的情况下捕获Python中的回车键

时间:2016-02-21 06:03:18

标签: python python-2.7

如果按下回车键,我需要在Python中重启我的程序。我找到了这个问题和解决方案:how to check if the enter key is pressed python。然而当我用googled 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'

此外,如果我按任何其他键,它只会在空闲状态下打印,程序不会退出。

顺便说一下,我知道必须有一个更好的方法来使用列表或词典来编程,但这就是我所知道的。

1 个答案:

答案 0 :(得分:1)

import random as rn class Piece(): def __init__(self): #vals = [top, right, bottom, left] self.vals = [rn.randint(10,99) for _ in range(4)] self.n = 4 def rotate_left(self): self.vals = [self.vals[i-self.n+1] for i in range(self.n)] def rotate_right(self): self.vals = [self.vals[i-1] for i in range(self.n)] def get_vals(self): return self.vals 将导致零长度字。做你的第一次检查。

然而,如果你想捕捉一个单一的关键字,比如C中的getch(),它就会复杂得多,例如https://stackoverflow.com/a/6599441/493161

另一种选择是捕获^ C(control-C):

enter