Reputation: 2442
I would like to close the File Open dialog after selecting a file. Currently with my code, I can select a file but the File Open dialog remains open until I click the 'X'. How can I close this window after I have selected a file.
Here is my code:
import sys
from tkinter import *
from tkinter.filedialog import askopenfilename
fname = "unassigned"
def openFile():
global fname
fname = askopenfilename()
if __name__ == '__main__':
b = Button(text='File Open', command = openFile).pack(fill=X)
mainloop()
print (fname)
Upvotes: 4
Views: 21297
Reputation:
The file dialog is closing just fine. I think what you are trying to say is that the Tkinter window you created to hold the button is not closing after you select a file from the dialog. To have it do this, you will need to restructure your program a bit.
First, you need to explicitly create a Tk
window to hold the button:
root = Tk()
You should then list this window as the button's parent:
Button(root, text='File Open', command = openFile).pack(fill=X)
# ^^^^
Finally, you should call the destroy
method of the root
window at the end of openFile
:
root.destroy()
This will cause the window to close and the Tkinter mainloop to exit.
In all, your script will look like this:
import sys
from tkinter import *
from tkinter.filedialog import askopenfilename
fname = "unassigned"
def openFile():
global fname
fname = askopenfilename()
root.destroy()
if __name__ == '__main__':
root = Tk()
Button(root, text='File Open', command = openFile).pack(fill=X)
mainloop()
print (fname)
Upvotes: 9