马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 player-none 于 2024-12-1 16:50 编辑
第一次发文章,格式不恰当请见谅
我去研究了下,怎么让 Pygame 接受中文输入,搜到的方法:
os.environ['SDL_IME_SHOW_UI'] = '1'
...
elif event.type == pygame.TEXTINPUT:
print(event.text)
试了下,原本输入中文 Pygame 都不会显示的,现在在窗口右下角显示了一条输入法的打字内容,可以正常输入了。
后来研究 pygame.key.xxxx 的时候,无意间发现了这几个函数:
tutu.to/image/R1Pjd
查官网:
pygame.key.set_text_input_rect()
controls the position of the candidate listset_text_input_rect(Rect) -> None
This sets the rectangle used for typing with an IME. It controls where the candidate list will open, if supported.
也就是说,这个函数可以设置使用 IME 输入时的矩形区域。
经测试,实际起作用的参数只有前两个,后两个需要象征性地输入。调用实例:
pygame.key.set_text_input_rect((输入法最左侧x, 输入法最上侧y, 0, 0))
在 UI 中,用于解决输入框问题:
pygame.key.set_text_input_rect((输入框left, 输入框bottom, 0, 0))
其他两个函数的文档如下:
pygame.key.start_text_input()
start handling Unicode text input events
start_text_input() -> None
Start receiving pygame.TEXTEDITING and pygame.TEXTINPUT events. If applicable, show the on-screen keyboard or IME editor.
For many languages, key presses will automatically generate a corresponding pygame.TEXTINPUT event. Special keys like escape or function keys, and certain key combinations will not generate pygame.TEXTINPUT events.
In other languages, entering a single symbol may require multiple key presses, or a language-specific user interface. In this case, pygame.TEXTINPUT events are preferable to pygame.KEYDOWN events for text input.
A pygame.TEXTEDITING event is received when an IME composition is started or changed. It contains the composition text, length, and editing start position within the composition (attributes text, length, and start, respectively). When the composition is committed (or non-IME input is received), a pygame.TEXTINPUT event is generated.
Text input events handling is on by default.
pygame.key.stop_text_input()
stop handling Unicode text input events
stop_text_input() -> None
Stop receiving pygame.TEXTEDITING and pygame.TEXTINPUT events. If an on-screen keyboard or IME editor was shown with pygame.key.start_text_input(), hide it again.
Text input events handling is on by default.
To avoid triggering the IME editor or the on-screen keyboard when the user is holding down a key during gameplay, text input should be disabled once text entry is finished, or when the user clicks outside of a text box.
- pygame.key.start_text_input(): 开始接收输入
- pygame.key.stop_text_input(): 停止接收输入
文中加粗的部分体现了 pygame.TEXTINPUT 事件和 pygame.KEYDOWN 事件接收范围的不同:前者不接收 Esc、功能键等。这确实是 pygame.TEXTINPUT 相较于 pygame.KEYDOWN 的优势。
对其提到的 pygame.TEXTEDITING 事件,作用相较于 pygame.TEXTINPUT 不大,它用来接收输入法的改变,确切地说,是 text_input 接收和不接收状态的改变。
—————————————————————————————————————————————————————
- 对于输入框中文本的显示不做赘述,这个简单,添加重新绘制输入框的函数即可,或者把 text 属性搞个 @property;
- 对于切换输入状态(接不接收输入事件),可以在鼠标点击输入框的时候做出判断,点击到输入框所在的 rect,就 start,否则 stop,然后设置输入法显示的位置,前文有提到:pygame.key.set_text_input_rect((输入框left, 输入框bottom, 0, 0))
|