How to use Tkinter to open file in folder using dropdown
You cannot just select and read a file's contents from tkinter. You have to write some other scripts for that reading part.
What the selection of filename does from tkinter combo box
, is nothing but, get the particular file name as a string
type.
However, in Python it's pretty straight forward to read a .xlsx file
.You can use Pandas
module for that.
I have written the code for you to read the file, (but you have to install pandas)
from functools import partialimport osimport tkinter as tkfrom tkinter import ttk#import tkinter as tkfrom tkinter import filedialog, messagebox, ttkimport pandasdef get_selected_file_name(file_menu): filename = file_menu.get() print("file selected:", filename) reader = pandas.read_excel(filename) # code to read excel file # now you can use the `reader` object to get the file datafolder = os.path.realpath('./test_folder')filelist = [fname for fname in os.listdir(folder)]master = tk.Tk()master.geometry('1200x800')master.title('Select a file')optmenu = ttk.Combobox(master, values=filelist, state='readonly')optmenu.pack(fill='x')button_select = tk.Button(master, text="Read File", width=20, height=7, compound=tk.CENTER, command=partial(get_selected_file_name, optmenu))button_select.pack(side=tk.RIGHT)master.mainloop()
The window should look somewhat like this:
I'd explore using the filedialog module in tkinter.
import tkinter as tkfrom tkinter import filedialogdef load_file(): f_in = filedialog.askopenfilename( filetypes = [ ( 'Python', '*.py' ) ]) # Change to appropriate extension. if len( f_in ) > 0: with open( f_in, 'r' ) as file: filedata = file.read() print( filedata ) # printed to the terminal for simplicity. # process it as required.root = tk.Tk()tk.Button( root, text = 'Find File', command = load_file ).grid()root.mainloop()
askopenfilename
allows a user to navigate the folder tree to find the correct file. Basic documentation