3

I'm trying to simply get a file name from the user by tkinter.filedialog.askopenfilename(). The function returns fine and the code below displays the file name okay but the dialog window doesn't close immediately after hitting 'open' or 'cancel', it freezes. I'm using python 3.3.3 or OSX 10.9.1 and tcl/tK 8.5.9.

from tkinter import *
from tkinter.messagebox import *
from tkinter.filedialog import *

top = Tk()
top.withdraw()

file_name = filedialog.askopenfilename()

print (file_name)
Drewness
  • 5,004
  • 4
  • 32
  • 50
John Bell
  • 31
  • 1
  • 3
  • Have you tried opening the dialog _after_ starting the event loop? OSX has its share of tkinter idiosyncrasies, but generally speaking tkinter needs an event loop to be running in order to function properly. – Bryan Oakley Feb 27 '14 at 01:11
  • Bryan, by 'an event loop' do you mean mainloop()? – John Bell Feb 27 '14 at 17:53

3 Answers3

0

Adding root.update() after filedialog.askopenfilename() gets the open file dialog to close after the file is chosen.

root = tk.Tk()                     
root.withdraw()
file_path = filedialog.askopenfilename()
root.update()

Refer to: Tkinter askopenfilename() won't close

SparkAndShine
  • 17,001
  • 22
  • 90
  • 134
0

A work around that I used for this is to "withdraw" the tkinter window AFTER selecting the file from file explorer. Here is the code snippet I used -

import tkinter
from tkinter import filedialog

def selectCustomerFileTK():
    root = tkinter.Tk()
    root.wm_attributes('-topmost', 1)
    filename = filedialog.askopenfilename()
    root.withdraw()
    return filename

getfile = selectCustomerFileTK()

It opens a tkinter window while you are selecting the file, but the moment you select the file and press "Open", the tkinter window and file explorer both close because of the "root.withdraw()" command after.

-2

You don't need to specify module name in

file_name = filedialog.askopenfilename()

Try

file_name = askopenfilename()

instead