Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
让python响应特定的按键_Python_Keyboard - Fatal编程技术网

让python响应特定的按键

让python响应特定的按键,python,keyboard,Python,Keyboard,我试图创建一个程序,逐行读取文本文件中的文本。对于前3行,用户只需按enter键即可前进到下一行。但是,对于第四行,他们需要按一个特定的键,在本例中为字母u。我尝试使用getch来实现这一点,但由于某些原因,按u键不会产生任何响应。代码如下: from os import path from msvcrt import getch trial = 1 while trial < 5: p = path.join("C:/Users/Work/Desktop/Scripts/Coge

我试图创建一个程序,逐行读取文本文件中的文本。对于前3行,用户只需按enter键即可前进到下一行。但是,对于第四行,他们需要按一个特定的键,在本例中为字母u。我尝试使用getch来实现这一点,但由于某些原因,按u键不会产生任何响应。代码如下:

from os import path
from msvcrt import getch
trial = 1
while trial < 5:
    p = path.join("C:/Users/Work/Desktop/Scripts/Cogex/item",  '%d.txt') % trial
    c_item = open(p) 
    print (c_item.readline())
    input()
    print (c_item.readline())
    input()
    print (c_item.readline())
    input()
    print (c_item.readline())
    if ord(getch()) == 85:
        print (c_item.readline())
        input()
trial += 1

我也读过关于人们使用pygame或Tkinter的文章,但我不知道如果程序不使用图形界面,是否可以使用它们。提前谢谢

问题在于,大多数现代TTY上的输入都是缓冲的-只有在按下enter键时才会发送到应用程序。您也可以在C中测试这一点。如果您创建一个GUI应用程序,直接从操作系统获取其键盘数据,那么是的,您可以这样做。然而,这可能比仅仅要求用户在按u之后打印enter键更麻烦。 例如:

result = input()
if result == 'u':
    print(c_item.readline())
    input()
85是大写字母“U”的序号。对于小写字母“u”,您需要序号117

您也可以简单地检查字符是否为b'u'

或者可以对序号执行不区分大小写的检查:

if ord(getch()) in (85, 117):
或对于字符串:

if getch().lower() == b'u'
您还需要将trial+=1移动到循环中:

if getch().lower() == b'u':
    print (c_item.readline())
    input()
trial += 1

键入“u”后是否按Enter键?在按下Enter键之前,您使用的终端可能不会向程序提供缓冲输入。如果没有GUI,这是很难解决的,因为这是终端的行为,而不是你的应用程序。谢谢你的建议。是的,我在键入“u”后按enter键。实际上,我可能会选择GUI选项……最终会更简单。谢谢你的建议!然而,这仍然不能解决问题……我尝试了您描述的所有方法,但仍然无法让python响应大写或小写的“u”。如果你还有其他想法,我很乐意听听
if getch().lower() == b'u'
if getch().lower() == b'u':
    print (c_item.readline())
    input()
trial += 1