使用PySimpleGui,如何使按钮起作用?

4

第一次尝试使用PySimpleGui,想创建一个可执行程序,允许用户将目录/文件移动或复制到他们选择的目标位置,但不太明白如何将操作链接到按钮。

我的当前程序如下所示:

import PySimpleGUI as sg
import shutil, errno
src = ""
dest = ""
def copy(src, dest):
    try:
        shutil.copytree(src, dest)
    except OSError as e:
        # If the error was caused because the source wasn't a directory
        if e.errno == errno.ENOTDIR:
            shutil.copy(src, dest)
        else:
            print('Directory not copied. Error: %s' % e)

#Me testing out commands in PSG
layout = [[ sg.Text("Select path from source to 
destination")],
[sg.Text("Source Folder", size=(15,1)), sg.InputText(src), 
sg.FolderBrowse()],
[sg.Text("Destination Folder", size=(15,1)), 
sg.InputText(dest), sg.FolderBrowse()],
[sg.Button("Transfer", button_color=("white", "blue"), size= 
(6, 1)),sg.Button(copy, "Copy", button_color=("white", 
"green"), size=(6, 1)),sg.Exit(button_color=("white", "red"), 
size=(6, 1))]]

event = sg.Window("Mass File Transfer").Layout(layout).Read()

从我能够清晰理解的内容来看,我认为将复制命令纳入按钮属性中会将其链接到先前在代码中定义的命令。我将src和dest输入留空,并添加浏览文件夹扩展以便更轻松地管理文件。


我认为主程序误解了PySimpleGUI与主要GUI框架没有类似的API和架构。它不遵循它们的惯例。与其尝试使用回调模型,事件是在简单的事件循环中处理的。 - Mike from PSG
1个回答

5
没有将按钮链接到功能或回调函数。
要实现您想要的功能,当您从读取操作中收到“复制按钮”事件时,请调用复制操作。
我建议您仔细阅读文档,了解有关Button等调用如何工作的信息。请访问http://www.PySimpleGUI.org
以下是我认为您希望代码执行的内容:
import PySimpleGUI as sg
import shutil, errno
src = ""
dest = ""
def copy(src, dest):
    try:
        shutil.copytree(src, dest)
    except OSError as e:
        # If the error was caused because the source wasn't a directory
        if e.errno == errno.ENOTDIR:
            shutil.copy(src, dest)
        else:
            print('Directory not copied. Error: %s' % e)

#Me testing out commands in PSG
layout = [[ sg.Text("Select path from source to destination")],
[sg.Text("Source Folder", size=(15,1)), sg.InputText(src),
sg.FolderBrowse()],
[sg.Text("Destination Folder", size=(15,1)),
sg.InputText(dest), sg.FolderBrowse()],
[sg.Button("Transfer", button_color=("white", "blue"), size=
(6, 1)),sg.Button("Copy", button_color=("white",
"green"), size=(6, 1)),sg.Exit(button_color=("white", "red"),
size=(6, 1))]]

window = sg.Window("Mass File Transfer").Layout(layout)

while True:
    event, values = window.Read()
    print(event, values)
    if event in (None, 'Exit'):
        break

    if event == 'Copy':
        copy(values[0], values[1])

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