Home > OS >  Using tkinter Entry as a Path in os.walk?
Using tkinter Entry as a Path in os.walk?

Time:05-10

I like to enter a Path with a Tkinter Entry, which the becomes part of a Programm, which uses os.walk.
The Programm print all entries with their paths (later I will add more).

My Problem is, that I get an error before even entering something in tkinter.

My code looks like this:

import os 
def run_exe():
       root_path= root_path_entry
       for root, subfolders, filenames in os.walk(root_path):
          print( os.path.join(root, filename))

master = tk.Tk ()

root_path_label= tk.Label(master, text= "Root Here")
root_path_entry= tk.Entry(master)

Enter_Button= tk.Button(master, text="Start", command= run_exe())

root_path_label.grid (row=1, column=0)
root_path_entry.grid (row=1, column=1)
Enter_Button.grid(row=2, column=1)


mainloop()

Any ideas?

The Traceback looks like this:

TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_920/1950915600.py in <module>
     12 root_path_entry= tk.Entry(master)
     13 
---> 14 Enter_Button= tk.Button(master, text="Start", command= run_exe())
     15 
     16 root_path_label.grid (row=1, column=0)

~\AppData\Local\Temp/ipykernel_920/1950915600.py in run_exe()
      4 def run_exe():
      5     root_path= root_path_entry
----> 6     for root, subfolders, filenames in os.walk(root_path):
      7         print( os.path.join(root, filename))
      8 

~\anaconda3\lib\os.py in walk(top, topdown, one rror, followlinks)
    340     """
    341     sys.audit("os.walk", top, topdown, one rror, followlinks)
--> 342     return _walk(fspath(top), topdown, one rror, followlinks)
    343 
    344 def _walk(top, topdown, one rror, followlinks):

TypeError: expected str, bytes or os.PathLike object, not Entry

CodePudding user response:

Try like this :

from tkinter import *
import os

def run_exe():
    root_path= input_variable.get()
    for root, dirnames, filenames in os.walk(root_path):
        for filename in filenames:
            print( os.path.join(root, filename))
    
window = Tk()

# Create widgets
input_variable = StringVar(window)
input_variable_label= Label(window, text= "Root Here").grid(row=1, column=0)
entry_variable = Entry(window, textvariable=input_variable).grid(row=1, column=1)

button_submit = Button(window, text="Start",command=run_exe).grid(row=2, column=1)

window.mainloop()

Output :

C:\Data\Config\test.ini
C:\Data\Config\nice\test.json
  • Related