使用PySimpleGui,如何让按钮工作?

问题描述 投票:1回答:1

第一次尝试使用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的输入,并添加了浏览文件夹扩展,以便于文件管理。

python python-3.x button file-transfer pysimplegui
1个回答
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])
© www.soinside.com 2019 - 2024. All rights reserved.