PySimpleGUI:按下按钮时调用函数

8
import PySimpleGUI as sg
import os

    layout = [[sg.Text('Velg mappe som skal tas backup av og hvor du vil plassere backupen')],
              [sg.Text('Source folder', size=(15, 1)), sg.InputText(), sg.FolderBrowse()],
              [sg.Text('Backup destination ', size=(15, 1)), sg.InputText(), sg.FolderBrowse()],
              [sg.Text('Made by Henrik og Thomas™')],
              [sg.Submit(), sg.Cancel()]]
    window = sg.Window('Backup Runner v2.1')

    event, values = window.Layout(layout).Read()

我怎样在按下提交按钮或任何其他按钮时调用一个函数?


我刚刚在我的回答中补充了一点,你不必添加事件循环。你可以把“if”语句放在你的最后一行代码之后,即Read调用之后。感谢您将问题标记为已解决。 - Mike from PSG
1个回答

9
在 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 Loop
    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()   # from OP's existing code
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 Loop
    event, values = window.read()
    if event in (None, 'Exit'):
        break
    if callable(event):
        event()
    elif event == '3':
        func('Button 3 pressed')

window.close()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接