22

I'm using the following code snippet to open a file chooser dialog box. It opens up the dialog fine, but after a file is chosen the dialog box stays open for the duration of the execution of the rest of my code, which is 3-4 min. I thought root.destroy() would close the open file dialog like it closes other Tkinter windows but that doesn't seem to be the case.

from tkinter import *
from tkinter.filedialog import askopenfilename

root = Tk()
root.withdraw()
file_path = askopenfilename()
root.destroy()

How would I go about getting the open file dialog to close after the file is chosen? I'm using version 3.4.3 on OSX 10.10

mmmkay
  • 696
  • 1
  • 7
  • 12
  • Works fine on Windows 7, Python 2.7 – VRage Aug 26 '15 at 04:56
  • 1
    Forget root window and want coming back ? `root.withdraw()` you lose root window can't go back ! – dsgdfg Aug 26 '15 at 05:08
  • @SDilmac `root.deiconify()` to bring it back – maccartm Aug 26 '15 at 14:30
  • 1
    I'm not sure if it's different on OSX, but I'm more interested in closing the dialog box after the file selection, while the program finishes it's execution. If you add `time.sleep(10)` the dialog windows stays open while python waits 10 seconds. I want it to close immediately after file selection. – mmmkay Aug 26 '15 at 16:27
  • @maccartm friend, can you show me `root.deiconify()` in code ? But Thank you for warning me .... – dsgdfg Aug 26 '15 at 17:53
  • 1
    @SDilmac to avoid starting a discussion in this user's question, simply use `root.withdraw()` to hide the root window and then call `root.deiconify()` to bring it back, that's all there is to it. With `withdraw`, the window still exists, it's just hidden. `deiconify` will un-minimize it, or in this case, bring it back. – maccartm Aug 26 '15 at 19:16
  • Found the answer in another thread [link](http://stackoverflow.com/questions/21866537/what-could-cause-an-open-file-dialog-window-in-tkinter-python-to-be-really-slow). Needed to add `root.update()` before calling `askopenfilename()` – mmmkay Aug 26 '15 at 21:35
  • @mmmkay You could probably answer your own question with a code snippet. Thanks for posting the solution! – sevenboarder Oct 23 '15 at 16:00

1 Answers1

25

For the sake of closing this question, here is the answer:

Call root.update() before askopenfilename()

Jonah Fleming
  • 1,187
  • 4
  • 19
  • 31