Here is a simple example of getting the filenames inside of a given directory and displaying them as buttons to be selected from.
This example will only work with a directory containing only text files but it should serve to provide a good example.
Here I use the os
import and use the method from os
called listdir()
. This will allow me to iterate over all the file names in a given directory. In this case my directory is to a folder that is on the same level as my .py
file.
I have created a method called find_text_file
that will create a pop up window using Toplevel()
and then create a button for every file name within that directory. These buttons will run two commands. One command to destroy the Toplevel window and another will call the method update_textbox
to append the text file to the text box on the root window.
Keep in mind this only works with text files. You may need to do a little extra to work with json files and even more for other formats. (Most formats are not compatible with tkinter).
Make sure you change self.file_path
to be the path to your text files.
import tkinter as tk
import os
class MyApp(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.root = parent
self.text = tk.Text(self.root, width=50, height=20)
self.text.pack()
self.file_path = "./TextFiles"
tk.Button(self.root, text="Open text file", command= self.find_text_file).pack()
def find_text_file(self):
self.top = tk.Toplevel(self.root)
for name in os.listdir(self.file_path):
tk.Button(self.top, text=name, command = lambda n=name: [self.top.destroy(), self.update_textbox(n)]).pack()
def update_textbox(self, name):
with open("{}/{}".format(self.file_path, name), "r") as f:
self.text.delete("1.0", "end")
self.text.insert("1.0", f.read())
if __name__ == "__main__":
root = tk.Tk()
app = MyApp(root)
tk.mainloop()
solved A window which displays all the files(.txt, .docs, .docx, .pdf) of a folder/directory in python [closed]