【问题标题】:PySimpleGUI call a function when pressing buttonPySimpleGUI 在按下按钮时调用一个函数
【发布时间】:2019-08-26 04:35:06
【问题描述】:
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 调用)之后。感谢您将问题标记为已回答。

标签: python pysimplegui


【解决方案1】:

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

使用回调来指示按钮按下的其他 Python GUI 框架并不多。相反,所有按钮按下都作为“事件”返回,从读取调用返回。

要获得类似的结果,您需要检查事件并自己调用函数。

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

【讨论】:

    猜你喜欢
    • 2016-10-24
    • 2013-02-11
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多