有没有办法绑定键盘按键以有效地按下 PySimpleGUI 中的按钮?

问题描述 投票:0回答:1

在 PySimpleGUI 中,似乎只有鼠标单击才会触发事件。我已阅读文档并搜索网络。提到的唯一将启动事件的键盘键是返回键。我想要做的是按下键盘上的 h 键而不是使用鼠标来按下 Hello 按钮(在下面的代码中)?只是想知道我是否缺少某个调用或函数?

import PySimpleGUI as sg
layout = [[sg.Button('Hello'),]]
window = sg.Window('Demo', layout)
while True:
    event, values = window.read()
    if event == sg.WINDOW_CLOSED:
        break
    if event == 'Hello':
        print('Hello, World!')
window.close()
python keyboard-events pysimplegui
1个回答
0
投票

PySimpleGUI 不支持开箱即用的键盘事件。 window.read() 函数仅返回来自 GUI 元素(如按钮、输入字段等)的事件。它不捕获键盘事件。

但是,您可以使用bind方法将键盘事件绑定到窗口。以下是修改代码以使其正常工作的方法:

import PySimpleGUI as sg

layout = [[sg.Button('Hello', key='-HELLO-', bind_return_key=True)]]

window = sg.Window('Demo', layout, return_keyboard_events=True)

while True:
    event, values = window.read()
    if event == sg.WINDOW_CLOSED:
        break
    if event == '-HELLO-' or event == 'h':  # If 'h' key is pressed
        print('Hello, World!')

window.close()

在此代码中,return_keyboard_events=True 添加到 sg.Window 调用中。这使得窗口返回键盘事件。现在,当按下“h”键时,将返回事件“h”和“Hello, World!”消息已打印。

© www.soinside.com 2019 - 2024. All rights reserved.