PySimpleGUI 按下按钮时调用函数

Kic*_*dak 8 python pysimplegui

import PySimpleGUI as sg\nimport os\n\n    layout = [[sg.Text('Velg mappe som skal tas backup av og hvor du vil plassere backupen')],\n              [sg.Text('Source folder', size=(15, 1)), sg.InputText(), sg.FolderBrowse()],\n              [sg.Text('Backup destination ', size=(15, 1)), sg.InputText(), sg.FolderBrowse()],\n              [sg.Text('Made by Henrik og Thomas\xe2\x84\xa2')],\n              [sg.Submit(), sg.Cancel()]]\n    window = sg.Window('Backup Runner v2.1')\n\n    event, values = window.Layout(layout).Read()\n
Run Code Online (Sandbox Code Playgroud)\n

当我按下提交按钮时如何调用函数?或任何其他按钮?

\n

Mik*_*eyB 9

PySimpleGUI 文档在事件/回调部分讨论了如何执行此操作 https://pysimplegui.readthedocs.io/#the-event-loop-callback-functions

与其他 Python GUI 框架不同的是,它使用回调来发出按钮按下的信号。相反,所有按钮按下都会作为从 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()
Run Code Online (Sandbox Code Playgroud)

要查看此代码在线运行,您可以使用网络版本在此处运行它: 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')
Run Code Online (Sandbox Code Playgroud)

[ 2020 年 11 月编辑 ] - 可调用按键

这不是一个新功能,只是之前的答案中没有提及。

您可以将键设置为函数,然后在事件生成时调用它们。下面是一个使用几种方法来执行此操作的示例。

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()
Run Code Online (Sandbox Code Playgroud)