Im new to python UI.
I have a folder with 60+ text files (txt1, txt2, etc), each contains a list of names.
in my Python UI, I have 2 combo boxes. I want the first one to allow me to select a text file from the list of txt files available in folder path, and once the file is selected(combo box1), to populate the second combo box with the names inside txt file selected from combo1. is that possible? and if it is, how to do it?
You have my gratitude in advance.
Thanks much for the help!
For Combo box1 :
def combolistdisp(combo):
os.chdir("./")
ls=[]
for file in glob.glob("*.sql"):
#print(file)
ls.append(file)
combo['values']=(ls)
For Combo Box2:
I need help how to read the file selected from combo box1 and populate combo box 2 with the contents inside file.
Yeah it is possible.
You can follow these functions to do that.Firstly, fetch the list of txt files in the specified directory with txt_files
def populate_combo1():
folder_selected = filedialog.askdirectory()
if folder_selected:
folder_path.set(folder_selected)
txt_files = [file for file in os.listdir(folder_selected) if file.endswith('.txt')]
comboBox1['values'] = txt_files
Then read the lines of the selected file and populate with comboBox2['values'] = [line.strip() for line in file]
import os
import tkinter as tk
from tkinter import ttk, filedialog
def populate_combo2(event):
selected_file = comboBox1.get()
if selected_file:
with open(os.path.join(folder_path.get(), selected_file), 'r') as file:
comboBox2['values'] = [line.strip() for line in file]
root = tk.Tk()
root.title("File Selector")
folder_label = tk.Label(root, text="Select Folder Path:")
folder_label.grid(row=0, column=0, padx=5, pady=5, sticky='w')
folder_path = tk.StringVar()
folder_entry = ttk.Entry(root, textvariable=folder_path, width=40)
folder_entry.grid(row=0, column=1, padx=5, pady=5, sticky='ew')
folder_button = ttk.Button(root, text="Browse", command=populate_combo1)
folder_button.grid(row=0, column=2, padx=5, pady=5)
comboBox1_label = tk.Label(root, text="Select a txt File:")
comboBox1_label.grid(row=1, column=0, padx=5, pady=5, sticky='w')
comboBox1 = ttk.Combobox(root, width=37)
comboBox1.grid(row=1, column=1, padx=5, pady=5, sticky='ew')
comboBox2_label = tk.Label(root, text="Contents of Selected File:")
comboBox2_label.grid(row=2, column=0, padx=5, pady=5, sticky='w')
comboBox2 = ttk.Combobox(root, width=37)
comboBox2.grid(row=2, column=1, padx=5, pady=5, sticky='ew')
comboBox1.bind("<<ComboboxSelected>>", populate_combo2)
root.mainloop()