Reputation: 513
I create a small gui with a browse button where the user has to click to open the directory choose dialog. After the user selected a directory I want to display the selected path on the gui as a simple text.
How do I do it? If I put the
txt_path = tk.Label(master=root,textvariable=path)
txt_path.grid(row=1, column=0)
in the browse_button function there appears no text with the selected directory, only the print will work.
If I put
txt_path = tk.Label(master=root,textvariable=path)
txt_path.grid(row=1, column=0)
outside of the browse_button function then an error appears:
txt_path = tk.Label(master=root,textvariable=path) NameError: name 'path' is not defined
because the path variable is not defined yet- is the correct way to make the path variable global? My code:
from tkinter import filedialog
import tkinter as tk
def browse_button():
path = filedialog.askdirectory()
if len(path) > 0:
print('OK: ' + path)
# txt_path = tk.Label(master=root,textvariable=path)
# txt_path.grid(row=1, column=0)
else:
print('ERROR')
###########################################################
# GUI
root = tk.Tk()
root.geometry("650x400")
btn_Browse = tk.Button(text="Browse", command=browse_button)
btn_Browse.grid(row=0, column=0)
txt_path = tk.Label(master=root,textvariable=path)
txt_path.grid(row=1, column=0)
root.mainloop()
Upvotes: 1
Views: 492
Reputation: 76
There's no need for a global variable. The problem is that you're trying to define the label's text as a variable that might stay undefined because it's first defined out of the main function. I fixed your code:
from tkinter import filedialog
import tkinter as tk
def browse_button():
path = filedialog.askdirectory()
if len(path) > 0:
print('OK: ' + path)
txt_path = tk.Label(master=root, text=path)
txt_path.grid(row=1, column=0)
else:
print('ERROR')
###########################################################
# GUI
root = tk.Tk()
root.geometry("650x400")
btn_Browse = tk.Button(text="Browse", command=browse_button)
btn_Browse.grid(row=0, column=0)
root.mainloop()
I wrote the lines you put with comment again, with a little changee - I changed the attribute textvariable
to text
of the txt_path
label.
Upvotes: 1