dimi_fn
dimi_fn

Reputation: 164

How to fix: FilesBrowse() triggers Event even if File has not been Uploaded (PySimpleGUI)

Goal:

I'm trying to design a GUI with PySimpleGUI.

Situation:

FilesBrowse() allows the user to upload multiple files at the same time. This is functional; however, if the user tries to re-upload new files by clicking the "Browse" button again, but then cancels it and does not select any file, then the event seems to capture the last file that was previously selected.

For example, suppose that in the first iteration, the files file1, file2, and file3 are selected and submitted, and the subsequent code is executed. Now, suppose that the user clicks 'browse' again to upload another file, but regrets it and does not upload anything eventually. In this case, the list containing the values of the event will have file1, file2, file3, file3 (although it should be file1, file2, file3 only).

I have "enable_events" set to True, and this is the part of the code where I'm gathering the values of files:

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

How could I go about debugging and fixing this issue?

Upvotes: 0

Views: 1448

Answers (1)

Jason Yang
Jason Yang

Reputation: 13051

It depend on how you use 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. Another case, using a button to invoke sg.popup_get_file and update selected files somewhere by yourself.
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()

Upvotes: 0

Related Questions