[Python] How to show multiple file location paths with Tkinter in Python

Discussão em 'Python' iniciado por Stack, Julho 23, 2025.

  1. Stack

    Stack Membro Participativo

    While my script works as intended (mostly), it is unable to show the multiple file paths of a particular file name. I was able to get this script to work prior to using tkinter so I will show what it was prior and post tkinter.

    Before:

    file = "file_name.exe"
    for r,d,f in os.walk("c:\\"):
    for files in f:
    if files == file:
    print(os.path.join(r,files))


    This was able to function as expected, it would return all file paths which was great for finding the multiple locations of a single file saved within my computer. I wanted to make this script more user friendly by introducing a GUI so I can share it with my friends however the script will only output the first file path it locates, not all the possible file paths. Here is what the code looks like now with tkinter.

    from tkinter import *
    from tkinter import ttk
    import os

    def find_file(*args):
    try:
    file = str(file_name.get())
    for r,d,f in os.walk('C:\\'):
    for files in f:
    if files == file:
    file_path.set(os.path.join(r,files))
    except ValueError:
    pass

    root = Tk()
    root.title("Find File Path")

    mainframe = ttk.Frame(root,padding="3 3 12 12")
    mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
    root.columnconfigure(0, weight=1)
    root.rowconfigure(0, weight=1)

    file_name = StringVar()
    file_entry = ttk.Entry(mainframe, width=7, textvariable=file_name)
    file_entry.grid(column=2, row=1, sticky=(W, E))

    file_path = StringVar()
    ttk.Label(mainframe, textvariable=file_path).grid(column=2, row=2, sticky=(W, E))

    ttk.Button(mainframe, text="Find File", command=find_file).grid(column=3, row=3, sticky=W)

    ttk.Label(mainframe, text="File Name").grid(column=3, row=1, sticky=W)
    # ttk.Label(mainframe, text="is equivalent to").grid(column=1, row=2, sticky=E)
    ttk.Label(mainframe, text="File Path").grid(column=3, row=2, sticky=W)

    for child in mainframe.winfo_children():
    child.grid_configure(padx=5, pady=5)

    file_entry.focus()
    root.bind("<Return>", find_file)

    root.mainloop()


    Considering that the before section worked as expected and only some minimal changes occurred I am not too sure why this is not working this time. My guess is that it is with the .set() method, I saw in How to add multiple strings to a set in Python? that the solution to that user's problem was to use .update() instead, however that did not work for me, what happened was that this ultimately prevented anything from being printed in the window. At least with .set()I was able to get at least one value, however now there is nothing.

    Continue reading...

Compartilhe esta Página