无法阻止箭头键在 Python 中使用 curses 库回显到控制台

Cannot stop arrows keys from echoing to the console in Python with the curses library

下面是我的代码。我正在尝试制作一个简单的文本编辑器,我试图确保箭头键不会打印到控制台,但它仍然会打印。有什么帮助吗?

import curses

text = []


def main(screen):
    curses.curs_set(1)
    curses.noecho()

    while True:
        newChar = screen.getkey()

        if newChar != curses.KEY_LEFT or curses.KEY_RIGHT or curses.KEY_UP or curses.KEY_DOWN:
            text.append(newChar)

        screen.addstr(0, 0, "".join(text))
        screen.refresh()


curses.wrapper(main)```

getkey returns 一个字符串;将它与 curses.KEY_UP 之类的整数进行比较不会达到您的预期。

这个有效:

import curses

text = []


def main(screen):
    curses.curs_set(1)
    curses.noecho()

    while True:
        newChar = screen.getch()
        # newChar = screen.getkey()

        if newChar != curses.KEY_LEFT and curses.KEY_RIGHT and curses.KEY_UP and curses.KEY_DOWN:
            screen.addstr(0, 0, curses.keyname(newChar))

        screen.refresh()


curses.wrapper(main)

哎呀,我想通了。 if 语句中比较值的问题。解决了我自己的问题。 yippee

import curses

text = []


def main(screen):
        curses.curs_set(1)

        while True:
            newChar = screen.getch()

            if newChar not in [curses.KEY_LEFT, curses.KEY_RIGHT, curses.KEY_UP, curses.KEY_DOWN]:
                screen.addstr(0, 0, curses.keyname(newChar))
                screen.refresh()


curses.wrapper(main)