在 PySimpleGUI 文档的事件/回调部分
https://pysimplegui.readthedocs.io/#the-event-loop-callback-functions中讨论了如何实现此功能。与其他使用回调信号按钮按下的 Python GUI 框架不同,PySimpleGUI 返回所有按钮按下作为从 Read 调用返回的“事件”。为了实现类似的结果,您需要检查事件并自己进行函数调用。
import PySimpleGUI as sg
def func(message):
print(message)
layout = [[sg.Button('1'), sg.Button('2'), sg.Exit()] ]
window = sg.Window('ORIGINAL').Layout(layout)
while True:
event, values = window.Read()
if event in (None, 'Exit'):
break
if event == '1':
func('Pressed button 1')
elif event == '2':
func('Pressed button 2')
window.Close()
要在线查看此代码运行情况,您可以使用Web版在此处运行:
https://repl.it/@PySimpleGUI/Call-Func-When-Button-Pressed
添加于2019年4月5日
我还应该在我的回答中说明,您可以在调用Read之后立即添加事件检查。 您不必像我展示的那样使用事件循环。 它可能看起来像这样:
event, values = window.Layout(layout).Read()
if event == '1':
func('Pressed button 1')
elif event == '2':
func('Pressed button 2')
[ 2020年11月更新 ] - 可调用键
这并不是一项新功能,之前的回答中没有提到它。
您可以将键设置为函数,然后在事件生成时调用它们。以下是使用几种方法的示例。
import PySimpleGUI as sg
def func(message='Default message'):
print(message)
layout = [[sg.Button('1', key=lambda: func('Button 1 pressed')),
sg.Button('2', key=func),
sg.Button('3'),
sg.Exit()]]
window = sg.Window('Window Title', layout)
while True:
event, values = window.read()
if event in (None, 'Exit'):
break
if callable(event):
event()
elif event == '3':
func('Button 3 pressed')
window.close()