3
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()

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

4

1 回答 1

5

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()

要查看此代码在线运行,您可以使用网络版本在此处运行它: 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()
于 2019-04-04T13:30:21.053 回答