Python is an interpreter based language, So it read's the code line by line.
file_path = '' # First reads this
def OpenFile(): # then reads this function
global file_path
file_path = fd.askopenfilename()
print(file_path) # then this
The functions wont execute until you call it. You may have noticed that before printing file_path
you havnt called OpenFile
function, so the variable file_path
s value is ''.
I would to set focus on window.mainloop()
function. mainloop
is an important part of tkinter application as it tells Python to run Tkinter's Event loop. This method listens for events, such as button clicks or keypresses, and blocks any code that comes after it from running until you close the window where you called the method.
For more details of mainloop
see this answer.
The mainloop
checks if any event is been passed, if passed then only updates the tkinter window. mainloop
is actually a loop of update()
and update_idletask()
so it would only execute print(file_path)
once unless and untill you have called it multiple times or in another loop.
So there are 3 solution for your problem:
- Adding another button and printing through it.
def printing():
print(file_path)
print_button = Button(window,text='Click to print value:', command=printing)
print_button.pack()
- Using text variables:
from tkinter import *
from tkinter import filedialog as fd
import pyperclip
file_path = StringVar()
def OpenFile():
global file_path
file_path.set(fd.askopenfilename()) ###
window = Tk()
window.geometry('600x600')
Open_button = Button(window,text='Select File', command=OpenFile)
Open_button.pack()
a=Label(window,textvariable=file_path)
a.pack()
window.mainloop()
- Using
.config
:
def OpenFile():
global file_path
file_path = fd.askopenfilename()
a.config(text=file_path)