python - PySimpleGUI 按下按钮时调用函数

标签 python pysimplegui

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

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

最佳答案

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

关于python - PySimpleGUI 按下按钮时调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55515627/

相关文章:

python - Google App Engine Python simplejson 转义?

python - 从 Python 中的 Flask 路由调用 Linux Powershell 中的 .ps1 脚本

Python App Engine 队列任务

python - 有没有办法在删除后恢复内置函数?

json - PySimpleGUI 中从右到左的文本方向

python - 如何在 PySimpleGUI GUI 中接收数据?

python - 如何在 PySimpleGUIQt 中实现复选框功能?

python - 较长 PySimpleGUI 脚本的正确设计模式

python - PySimpleGui 右对齐框架中的按钮

python - 有没有办法使文档图像从任何位置垂直?