FilesBrowse() 函数将所有选定的文件作为一项

FilesBrowse() function takes all selected files as one item

我正在使用 PySimpleGUI 开发 GUI,我希望用户浏览多个文件,将每个文件放入一个数组中,并获取数组的长度。

但是 FilesBrowse() 将所有文件作为一个对象并且 len(posts) 代码给出输出“1”,即使我选择 10 个文件。

如何解决这个问题?

这是我的代码:

import PySimpleGUI as sg

global posts

posts = []

layouts =  [[sg.Text("Browse the XLSX file: "), sg.FilesBrowse(key=0)],
           [sg.Button('Start The Process')], [[sg.Button('Exit')]]]

window = sg.Window("Title", layouts)

while True:
    event, values = window.read()
    if event in (sg.WIN_CLOSED, 'Exit'):
        break
    posts.append(values[0])
    x = len(posts)
    print(x)

首先你应该看到你得到了什么 print(values[0]) - 你应该看到它在名称之间使用 ; - 所以你可以用 split(';')

拆分它
posts = values[0].split(';')

或者如果您想扩展现有列表,请使用 +=(而不是 append()

posts += values[0].split(';')

完整的工作代码

import PySimpleGUI as sg

posts = []  # it is global variable and it doesn't need `global posts`

layouts =  [
    [sg.Text("Browse the XLSX file: "), sg.FilesBrowse(key=0)],
    [sg.Button('Start The Process')],
    [sg.Button('Exit')]
]

window = sg.Window("Title", layouts)

while True:
    event, values = window.read()
    if event in (sg.WIN_CLOSED, 'Exit'):
        break

# --- after loop ---

if values[0]: # check if files were selected
    posts += values[0].split(';')

print('len:', len(posts))
print('posts:', posts)

编辑:

在某些系统上似乎 if 必须在 while

while True:
    event, values = window.read()
    if event in (sg.WIN_CLOSED, 'Exit'):
        break

    if values[0]: # check if files were selected
        posts += values[0].split(';')

    print('len:', len(posts))
    print('posts:', posts)

如果您点击 window 的关闭按钮,您可能会遇到问题。 是values return的值从window.read()编辑出来的,大部分时候会是None,所以不能得到values[0],那么

TypeError: 'NoneType' object is not subscriptable

要更新其他元素,sg.Filesbrowse return str 并使用 sg.BROWSE_FILES_DELIMITER';' 作为分隔符。因此,您可以使用方法 str.split(';') 获取文件列表。当然,你可以在事件循环中调用 sg.popup_get_file,它可能是 return strstr 的列表,这取决于选项 multiple_files.

演示代码在这里

import PySimpleGUI as sg

sg.theme('DarkBlue3')
sg.set_options(element_padding=(3, 3))

posts = []

layouts =  [
    [sg.Text("Browse the XLSX file: ")],
    [sg.Input(key='-INPUT-'), sg.FilesBrowse(file_types=(("xlsx Files", "*.xlsx"), ("ALL Files", "*.*")))],
    [sg.Button('Add'), sg.Button('Exit')],
    [sg.Multiline(size=(80, 25), key='-MULTILINE-')],
]

window = sg.Window("Title", layouts, finalize=True)
multiline = window['-MULTILINE-']
window['-INPUT-'].expand(expand_x=True)
while True:
    event, values = window.read()
    if event in (sg.WIN_CLOSED, 'Exit'):
        break
    elif event == 'Add':
        path = values['-INPUT-']
        if path:
            posts += path.split(";")
        multiline.print(f'len: {len(posts)}')
        multiline.print(f'posts: {posts}')

window.close()