2

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?

Henry
  • 3,472
  • 2
  • 12
  • 36

2 Answers2

4

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.

Henry
  • 3,472
  • 2
  • 12
  • 36
  • This seems hacky, but the advantage is that by leaving out `root.overrideredirect(True)`, the file dialog is represented in the task bar. (Unlike solutions that use `tkinter.Tk().withdraw()`) – root Feb 27 '22 at 11:21
-1
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.

Carl_M
  • 861
  • 1
  • 7
  • 14
Times
  • 27
  • 3
  • 1
    Thanks for the suggestion, I've tried this, but using `root.withdraw` causes the file dialog to not appear – Henry Dec 12 '19 at 10:53
  • @Henry For me, it does appear. – root Feb 27 '22 at 11:22
  • The problem with this solution is that it hides the file dialog from the task bar. If other windows are in front of the file dialog, you have to minimize each of those windows one by one, or look for the file dialog in the Task View rather than task bar. – root Feb 27 '22 at 11:23