Reputation: 3942
I'm trying to use filedialog.asksavefilename
to get a save file path. I am running this code in the IDLE shell and it's a text based interface. This is the function to get the save path:
def getPath():
root=tk.Tk()
root.lift()
root.attributes('-topmost',True)
root.after_idle(root.attributes,'-topmost',False)
path = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=(("Text Documents", "*.txt"),))
root.destroy()
The dialog opened behind other windows, so I used this to make the dialog appear at the front. This works, but there is still an empty window behind it which I don't want. I've tried using root.withdraw()
but this just hides everything. I'd like to have only the file dialog open without the empty tk window. Any ideas as to how to do this?
Upvotes: 2
Views: 2066
Reputation: 66
I had exactly the same requirement i.e. using some of the tkinter.filedialog functions from console apps or scripts rather than a GUI. All my searches for how to achieve it turned up answers involving the creation of a temporary tkinter root window and destroying it after using the dialog box. For years I used such a solution, but was always annoyed at the lag that it created (sometimes, randomly, quite long).
I recently discovered that you just have to invoke the dialog box function - no pesky root window required!
from tkinter import filedialog
def getPath(): # now barely worth writing as a function!
path = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=(("Text Documents", "*.txt"),))
return path
print(getPath())
This has been working for me with filedialog.askopenfilename, filedialog.askdirectory etc, and without the annoying lag. If only I had seen an answer like this earlier!
Please comment if it does not work on your system/version though.
Upvotes: 0
Reputation: 3942
I've found a way to achieve the desired effect:
def getPath():
root=tk.Tk()
root.overrideredirect(True)
root.attributes("-alpha", 0)
path = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=(("Text Documents", "*.txt"),))
root.destroy()
I've removed all of the unnecessary lift
and topmost
parts - they didn't help. I used root.overrideredirect(True)
to remove the title bar and root.attributes("-alpha", 0)
to make the window 100% transparent, so you can't see it. The only drawback is that the file dialog window flashes when it opens, but that's not too much of a problem.
Upvotes: 4
Reputation: 29
from tkinter import Tk
from tkinter.filedialog import asksaveasfilename
def get_path():
root = Tk()
root.withdraw()
path = asksaveasfilename()
root.destroy()
return(path)
print(get_path()) # to verify expected result
Is this the behavior you're looking for? Hope this helps.
Upvotes: 0