0

I've been trying to get the printed output into a variable. Whenever I call the function it just simply repeats the button process. I tried to utilize global, but it doesn't seem to work.

Help pls thanks.

from tkinter import *
from tkinter import filedialog
import tkinter as tk

def openFile():
    filepath = filedialog.askopenfilename(title="Open for me")
    print(filepath)
    window.destroy()

window = tk.Tk()
window.title("Insert Excel File")
window.geometry("200x200")
button = Button(text="Open",command=openFile,height=3,width=10)
button.pack()
window.mainloop()
1
  • It worked for me. Nothing wrong with the oode. Commented May 26, 2022 at 16:01

1 Answer 1

3

print , outputs the string to stdout it does not store the value in a variable, you'll need to store it yourself.

Since you're using a callback you can't return the value. The best way to implement this is to use classes, the bad way is to use a global variable to store the result

I'm assuming you are not familiar with classes, so a possible solution would be

from tkinter import *
from tkinter import filedialog
import tkinter as tk

path = ""
def openFile():
    global path
    path = filedialog.askopenfilename(title="Open for me")
    window.destroy()

window = tk.Tk()
window.title("Insert Excel File")
window.geometry("200x200")
button = Button(text="Open",command=openFile,height=3,width=10)
button.pack()
window.mainloop()

# do something with path e.g. print
print(path)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, is it possible you can show me the way with classes?
I won't show you straight away. If you want to learn about classes this is a good hands-on tutorial to begin with. Then try this to learn how the same concepts are applied in Tkinter. Then if you are still stuck, ask a new question. Good luck

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.