让 python 响应特定的按键

Getting python to respond to a specific key press

我正在尝试创建一个程序,逐行读取文本文件中的文本。对于前 3 行,用户只需按回车键即可前进到下一行。然而,对于第四行,他们需要按下一个特定的键(在本例中为字母 "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,但我不知道是否可以在不让程序使用图形界面的情况下使用它们。提前致谢!

这个问题是大多数现代 ttys 上的输入是缓冲的——只有在按下回车键时才会发送到应用程序。您也可以在 C 中对此进行测试。如果您创建一个直接从 OS 获取其键盘数据的 GUI 应用程序,那么是的,您可以这样做。但是,这可能比仅要求用户在按下 u 后打印回车键更麻烦。 例如:

result = input()
if result == 'u':
    print(c_item.readline())
    input()

85 是大写 'U' 的序数。对于小写 'u',您需要序数 117.

if ord(getch()) == 117:

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

if getch() == 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