Reputation: 117
whenever i print this
def callback():
file_name = askopenfilename(filetypes=(("Music File", "*.mp3"),
("Video files", "*.mpeg")))
file_name = file_name.split("/")[-1]
a = str(file_name)
return a
print a
file_name = Button(root, text="open", command=callback)
file_name.pack(side=Tkinter.TOP)
the output will be like this
.35430920L
but when i use global, it does print out the file name which i want
def callback():
global a
file_name = askopenfilename(filetypes=(("Music File", "*.mp3"),
("Video files", "*.mpeg")))
file_name = file_name.split("/")[-1]
a = str(file_name)
print a
file_name = Button(root, text="open", command=callback)
file_name.pack(side=Tkinter.TOP)
the output will be like this
"example.mp3"
Upvotes: 1
Views: 587
Reputation: 133919
The output happens in execution order. In your first example, the variable a
is given the value .35430920L
before the print a
runs, and chronologically the print
statement occurs before the file dialog is actually even opened, thus it is impossible to print the value of chosen file there.
In the latter case, being in the callback function, the result is already known. Notice that you do not even need a global variable for that case. (you can remove the global a
, unless you need the result outside of that function).
Tkinter uses event-driven programming paradigm, it calls callback functions for each occurring event. What you want to do for any larger program, is to wrap your application and widgets in a class, and store things like filenames in class attributes.
Upvotes: 2