You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PySimpleGUIQt如何实现点击按钮与按键盘a键触发同一事件

PySimpleGUIQt 绑定A键触发Button1事件修改方案

核心修改点

  • 先修正原代码笔误:创建Window时传入的布局参数应该是提前定义的layout变量,而非self._layout
  • 创建Window时添加return_keyboard_events=True参数,开启全局键盘按键事件返回
  • 在事件判断分支中,将event == 'a'和原有event == 'Button1'条件并列,共用同一段处理逻辑

修改后完整代码

import PySimpleGUIQt as sg

layout = [
            [sg.Button('Button1')],
            [sg.Button('Exit')],
        ]    

# 开启键盘事件返回
window = sg.Window('Mechanical Turk tool', layout, return_keyboard_events=True)

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == 'Exit':
        break
        
    # 同时匹配按钮点击和a键按下事件
    elif event == 'Button1' or event == 'a':
        # 如果需要支持大写A触发,可改为 event == 'Button1' or event in ('a', 'A')
        print("You pressed button 1")

window.close()

可选简化方案

如果不想修改事件判断逻辑,可以直接将a键事件绑定到Button1的触发事件上,写法如下:

import PySimpleGUIQt as sg

layout = [
            [sg.Button('Button1', key='-B1-')],
            [sg.Button('Exit')],
        ]    

window = sg.Window('Mechanical Turk tool', layout)
# 直接将a键按下事件绑定到按钮的key,按下a键等价于点击该按钮
window.bind('a', '-B1-')

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == 'Exit':
        break
        
    elif event == '-B1-':
        print("You pressed button 1")

window.close()

内容的提问来源于stack exchange,提问作者Niewasz Biznes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 09:12:03