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

时间:2019-03-21 15:31:21

标签: python python-3.x button file-transfer pysimplegui

第一次尝试PySimpleGui,想要创建一个exec程序,该程序允许用户将目录/文件移动或复制到他们选择的目标位置,但并没有真正理解如何将操作链接到按钮。

我当前的程序如下:

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

据我所能清楚地理解,我认为将copy命令包含在按钮的属性中会将其链接到代码前面定义的命令。我将src和dest留作src和dest的输入,并添加了一个浏览文件夹扩展名,以便于文件管理。

1 个答案:

答案 0 :(得分:1)

没有按钮与功能的“链接”,也没有回调函数。

要执行所需的操作,请在读取后返回“复制按钮”事件时调用复制。

我敦促您通读文档,以了解这些对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])