Python curses - textpad.Textbox() keyboard input not working with German umlauts

ε祈祈猫儿з 提交于 2019-12-10 17:45:25

问题


I'm trying to use the curses textpad.Textbox() function for text input. Everything is working fine so far, however, some keys don't get recognized, including the section sign (§) and all German umlauts (ä/ö/ü). I guess it's somehow related to the text encoding, but I have no idea how to fix this. My German keyboard layout works perfectly fine with input().

Here is some minimal example:

    import curses
    import curses.textpad as textpad

    try:
        stdtscr = curses.initscr()
        curses.cbreak()
        stdtscr.keypad(1)
        curses.noecho()

        textpad.Textbox(stdtscr).edit()

    finally:
        curses.nocbreak()
        stdtscr.keypad(0)
        curses.echo()
        curses.endwin()

回答1:


Just as in C, you should initialize the locale. It's spelled out in both the Python documentation:

Since version 5.4, the ncurses library decides how to interpret non-ASCII data using the nl_langinfo function. That means that you have to call locale.setlocale() in the application and encode Unicode strings using one of the system’s available encodings.

and the ncurses manual page:

   The  library uses the locale which the calling program has
   initialized.  That is normally done with setlocale:

           setlocale(LC_ALL, "");

 If the locale is not initialized, the library  assumes  that
 characters are printable as in ISO-8859-1, to work with cer-
 tain legacy programs.  You should initialize the locale  and
 not  rely on specific details of the library when the locale
 has not been setup.

Addressing the followup comment, textpad.py does not expect UTF-8 input in any case. Essentially it "validates" its input, decides it isn't ASCII and ignores it when it's not.

Python's curses binding provides an interface to wgetch, which (with ncurses) gives the individual bytes for the UTF-8. (X/Open Curses specifies a different function wget_wch, for which Python has no binding).

textpad.py could be modified to work around the curses binding by assembling the bytes into a Unicode value, but you'd need the setlocale as the first step.



来源:https://stackoverflow.com/questions/42510606/python-curses-textpad-textbox-keyboard-input-not-working-with-german-umlauts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!