3
votes

I am using tkinter asopenfilename to trigger a file chooser so as to read files from my local directory. My problem is that after the file is chosen, the window freezes and python is 'not responding'.

I've tried the answer from this post: Tkinter askopenfilename() won't close no luck.

Below is my code:

from tkinter import Tk
from tkinter.filedialog import askopenfilename

root = Tk()
root.withdraw() 
root.update()
filename = askopenfilename() 
print(filename)

Is there anything that I am missing? Let me know if you need more clarity. Thanks!

4
Works ok for me with Python 3.6.5 on win10. What versions and IDE are you using? - figbeam
I am using Python 3.6.3 on OSX. It's running on Jupyter Notebook - Daniel
Saw another question in which a comment stated: "Calling root.update() after askopenfilename() works". for OSX and python2. Maybe worth a try. - figbeam
yes, put root.update() after works! Thanks @figbeam - Daniel
I believe you do not need the .update() method for what you want to do. That entire line can be removed. Try that :). - Sun Bear

4 Answers

1
votes

I tried all above solutions but didn't seem to solve the same issue for me. The dialog box was opening but somewhere in the background.

Found this code elsewhere and it works like a charm for me. On windows 10 too, python 3.x, and using Jupyter Notebook.

Posting it here in case it could help others.

    import tkinter as tk
    from tkinter import filedialog
    root = tk.Tk()
    root.withdraw()
    root.call('wm', 'attributes', '.', '-topmost', True)
    file_path = filedialog.askopenfilename( 
    %gui tk
    print(file_path)

0
votes

I tried using root.update() after filename = askopenfilename() in my MacOS.

Following worked for me-

from tkinter import Tk
from tkinter.filedialog import askopenfilename
root = Tk()
root.withdraw() 
filename = askopenfilename() 
root.update()
print(filename)
0
votes

I had the same behavior on MacOS and adding the iPython magic %gui tk appears to be solving the issue:

from tkinter import Tk
from tkinter.filedialog import askopenfilename

%gui tk
root = Tk()
root.withdraw() 
filename = askopenfilename(multiple=True) 

print(filename)

From the docs:

%gui tk      # enable Tk event loop integration
-1
votes
askopenfilename doesn't work in windows


from tkinter import *
#from tkFileDialog import askopenfilename
import tkinter.filedialog

def callback():
    name= tkinter.filedialog.askopenfilenames() 
    print (name)

errmsg = 'Error!'
Button(text='File Open', command=callback).pack(fill=X)
mainloop()