【问题标题】:How to fix: FilesBrowse() triggers Event even if File has not been Uploaded (PySimpleGUI)如何修复:即使文件尚未上传,FilesBrowse() 也会触发事件 (PySimpleGUI)
【发布时间】:2021-11-12 04:37:35
【问题描述】:

目标

我正在尝试使用 PySimpleGUI 设计一个 GUI。

情况

FilesBrowse() 允许用户同时上传多个文件。这是功能性的;但是,如果用户尝试通过再次单击“浏览”按钮重新上传新文件,但随后取消它并且未选择任何文件,则该事件似乎捕获了之前选择的最后一个文件。

例如,假设在第一次迭代中,文件file1file2file3被选中并提交,随后代码被执行。现在,假设用户再次单击“浏览”以上传另一个文件,但后悔并最终没有上传任何内容。在这种情况下,包含 event 值的列表将包含 file1、file2、file3file3(虽然它应该是 file1file2file3)。

我将“enable_events”设置为True,这是我收集文件值的代码部分:

if event == "_key_":
  file_of_key = values["_key_"]
  # if at least one file has been uploaded:
  if file_of_key:
  # list containing the the files uploaded
    files_of_key += file_of_key.split(";") 

我该如何调试和修复这个问题?

【问题讨论】:

    标签: python user-interface file-upload pysimplegui


    【解决方案1】:

    这取决于你如何使用sg.FileBrowse

    1. Most of time, it work with an previous element sg.Input and Cancel button when select files means not to change the content of sg.Input, and another button to confirm or send the selection stored in sg.Input.
    import PySimpleGUI as sg
    
    sg.theme("DarkBlue3")
    sg.set_options(font=("Courier New", 12))
    
    layout = [
        [sg.Input(key='-INPUT-'), sg.FilesBrowse()],
        [sg.Button('OK')]
    ]
    window = sg.Window('Title', layout, finalize=True)
    
    while True:
    
        event, values = window.read()
        if event == sg.WINDOW_CLOSED:
            break
        print(event, values)
    
    window.close()
    
    1. 另一种情况,使用按钮调用sg.popup_get_file并自行在某处更新所选文件。
    import PySimpleGUI as sg
    
    sg.theme("DarkBlue3")
    sg.set_options(font=("Courier New", 12))
    
    layout = [
        [sg.Input(disabled=True, key='-INPUT-'), sg.Button('Browse')],
    ]
    window = sg.Window('Title', layout, finalize=True)
    
    while True:
    
        event, values = window.read()
        if event == sg.WINDOW_CLOSED:
            break
        elif event == 'Browse':
            files = sg.popup_get_file('', multiple_files=True, no_window=True)
            if files:
                window['-INPUT-'].update(';'.join(files))
            else:
                 window['-INPUT-'].update('')
    
    window.close()
    

    【讨论】:

      猜你喜欢
      • 2014-04-08
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2010-10-19
      相关资源
      最近更新 更多