Dropdown files list dependent from another dropdown folder list
The basic algorithm behind the code want can be split as follows:
- bind each option select signal of the first combobox to a function,
- that scans a directory and sets the available files to the second combobox.
Now, the important part for this operation is:
optmenu.bind("<<ComboboxSelected>>", onSelect)......def onSelect(event): folder_name = filelist[event.widget.current()] folder_path = os.path.join(folder, folder_name) print(f"folder selected:{folder_name}, folder_path:{folder_path}, index:{event.widget.current()}") global sub_files sub_files = [] for f_name in os.listdir(folder_path): sub_files.append(f_name) print(sub_files) optmenu1['values'] = sub_files # set sub directories to combobox
The complete code:
from tkinter import *from functools import partialimport osimport tkinter as tkfrom tkinter import ttk# import tkinter as tkfrom tkinter import filedialog, messagebox, ttkimport pandas as pdimport webbrowserfrom webbrowser import open as openlinkimport urllibdef open(file_menu): filename = file_menu.get() open_in_browser_link = f"file://{os.path.join(folder, filename)}" print(open_in_browser_link) webbrowser.open(open_in_browser_link)def clear_data(): # tv1.delete(*tv1.get_children()) return Nonedef onSelect(event): folder_name = filelist[event.widget.current()] folder_path = os.path.join(folder, folder_name) print(f"folder selected:{folder_name}, folder_path:{folder_path}, index:{event.widget.current()}") global sub_files sub_files = [] for f_name in os.listdir(folder_path): sub_files.append(f_name) print(sub_files) optmenu1['values'] = sub_files # set sub directories to comboboxfolder = os.path.realpath(r'C:\Users\TestFile')sub_files = []# folder = os.path.realpath(r'./testing')filelist = [fname for fname in os.listdir(folder)]master = tk.Tk()master.geometry('1200x800')master.title('THB')# Frame for TreeViewframe0 = tk.LabelFrame(master, text="Chapter", background="light grey")frame0.place(height=500, width=1200, rely=0.0, relx=0.0)optmenu = ttk.Combobox(frame0, values=filelist, state='readonly')optmenu.pack()optmenu.set("Chapter")optmenu.bind("<<ComboboxSelected>>", onSelect)optmenu1 = ttk.Combobox(frame0, values=[], state='readonly')optmenu1.pack()optmenu1.set("SubChapter")button_select = tk.Button(frame0, text="Show Data", width=15, height=2, compound=tk.CENTER, command=partial(open, optmenu1))button_select.place(relx=0.5, rely=0.5)button_select.pack(side=tk.TOP)master.mainloop()
Now, this code, opens the C:\Users\TestFile
folder, and scans each direcotry and sets to first combobox (optmenu
).
Then, when you select any one option in optmenu
, it calls the onSelect()
function. This onSelect
function, read all files available inside the folder selected in optmenu
, and shows the available files in optmenu1
.