使用pynput库触发不同按键时输出大小写异常问题求助
问题分析与解决
问题原因
德语QWERTZ键盘上输入;需要同时按下Shift键和对应按键(通常是Ö键位置,Shift+Ö生成;)。当你的Listener检测到key.char == ";"时,Shift键仍处于按下状态,而pynput的Controller.type()会模拟真实键盘输入,此时未释放的Shift会让所有字母输入变为大写。而Enter是独立按键,无修饰键残留,所以输出正常。
解决方案
方案1:输入前释放所有修饰键
修改execute_command方法,先检测并释放所有可能的修饰键,再执行输入操作:
def execute_command(self): # 释放所有按下的修饰键(Shift/Ctrl/Alt等) modifier_keys = [Key.shift, Key.shift_r, Key.ctrl, Key.ctrl_r, Key.alt, Key.alt_r] for key in modifier_keys: if self.keyboard.is_pressed(key): self.keyboard.release(key) # 执行输入 self.keyboard.type('Test from the execute command')
方案2:针对;按键单独处理修饰键
在检测到;按键时,先释放Shift键再触发命令:
def on_press(self, key): try: if key == Key.esc: self.stop() elif key == Key.enter: self.execute_command() elif key.char == ";": # 释放左右Shift键(德语键盘输入;依赖Shift) if self.keyboard.is_pressed(Key.shift): self.keyboard.release(Key.shift) if self.keyboard.is_pressed(Key.shift_r): self.keyboard.release(Key.shift_r) self.execute_command() except AttributeError: pass
验证
修改代码后重新运行,在记事本中按下;键,此时execute_command输出的内容会恢复正常大小写,因为修饰键已被提前释放。
内容的提问来源于stack exchange,提问作者1020rpz
相关产品推荐
相关产品推荐

