简体   繁体   中英

Open File Dialog freezes after tkinter askopenfilename method is called

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)

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

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.

You don't need to specify module name in

file_name = filedialog.askopenfilename()

Try

file_name = askopenfilename()

instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM