PySimpleGUI中Input搭配FilesBrowse组件选中文件顺序被自动排序的问题求助
Hey there! I’ve faced this exact frustration before—PySimpleGUI’s default FilesBrowse element automatically sorts your selected files alphabetically, which breaks workflows that depend on the order of selection. Here’s a straightforward fix that lets you keep the original order:
The Problem Root
PySimpleGUI’s built-in FilesBrowse uses the underlying tkinter file dialog under the hood, but it adds an extra sorting step to the returned file list. To bypass this, we can directly call the tkinter file dialog ourselves, which preserves the order you select files in.
Step-by-Step Solution
Instead of relying on the default FilesBrowse button, we’ll use a custom button and handle the file selection manually:
Modify Your Layout
Replace theSg.FilesBrowseelement with a regular button so we can hook into its click event:import PySimpleGUI as sg from tkinter import filedialog import tkinter as tk layout = [ [sg.Text("Images:", size=(6, 1)), sg.Input(key='-IN0-', size=(64, 1)), sg.Button('Select Files', key='-BROWSE-')] ]Handle the Browse Event
In your window’s event loop, add logic to open the tkinter file dialog when the button is clicked, then update the input field with the ordered file paths:window = sg.Window('Image Selection', layout) while True: event, values = window.read() if event == sg.WIN_CLOSED: break if event == '-BROWSE-': # Initialize a hidden tkinter root window (required for the dialog) root = tk.Tk() root.withdraw() # Open the file dialog—this returns files in the order you selected them selected_files = filedialog.askopenfilenames() if selected_files: # Format the paths the same way PySimpleGUI does (semicolon-separated) file_list_str = ';'.join(selected_files) # Update the input element with the ordered list window['-IN0-'].update(file_list_str) window.close()
Why This Works
The filedialog.askopenfilenames() function from tkinter returns the file paths exactly in the order you selected them (whether you click one by one or use Ctrl+click). By formatting the result to match PySimpleGUI’s default semicolon-separated string, you maintain the same user experience while keeping your desired selection order.
Notes
- This works with the default tkinter backend for PySimpleGUI. If you’re using the Qt or WxPython backends, you’d use their respective file dialog methods (e.g.,
QtWidgets.QFileDialog.getOpenFileNames()for Qt) which also preserve selection order. - You can customize the file dialog further (like setting a default directory or file types) by adding parameters to
askopenfilenames()—check the tkinter docs for available options.
内容的提问来源于stack exchange,提问作者Bruno Fonseca

