How to use tkinter filedialog without a window
Asked Answered
E

2

7

I would like to use the dialog boxes and message boxes without opening a tkinter window.

Can someone teach me how to disable the window, or how to recreate the window, or show me a different solution which allows me to do such things.

The messageboxes are the same all around, the one I want to try to take advantage of the most is filedialog.askopenfile, filedialog.askdirectory, filedialog.asksaveasfilename.

Elocution answered 6/6, 2015 at 3:4 Comment(3)
Welcome to StackOverflow. Did you try looking for tutorials online? Such as this by Googling: python-course.eu/tkinter_dialogs.php If so, please show effort, which is what you've done and tried, along with the code, that way we can help in a better way.Aziza
possible duplicate of How do I get rid of Python Tkinter root window?Retake
@Aziza What does your link have to do with the tkinter window from the question?Bourgogne
C
11

Something like this?

from Tkinter import *
import tkFileDialog
import tkMessageBox

Tk().withdraw()
tkFileDialog.askopenfilename()
tkMessageBox.showerror("message", "words")
Charlsiecharlton answered 10/6, 2015 at 18:59 Comment(1)
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.Bourgogne
R
1

I noticed a problem with .withdraw() while working with filedialogs in combination with pygame.

When using .withdraw() on the root window, the tkinter filedialog also disappears from the taskbar. This means that when the filedialog loses focus (like when you interact with another (pygame in my case) window by clicking it), the filedialog disappears and cannot be reopened by clicking the icon in your taskbar, but it's still active in the background, which permanently paused my pygame app. ("softlocking" the user)

The solution is to use iconify() instead of withdraw, which, as the name implies, does not remove the icon from the taskbar (allowing the user to reopen the window!), but it does minimise the window.

I ended up with this, after some experimentation:

import tkinter
from tkinter import filedialog

root = tkinter.Tk() # } execute these lines once, to "initialise" tkinter
root.iconify()      # }

def prompt_files():
    try:
        file_paths = filedialog.askopenfilenames()
        root.iconify()
    except tkinter.TclError: # this error was raised once or twice while testing, just in case return an empty list
        return []
    else:
        return file_paths
def stop_tk(): # call this when you're done selecting files, to stop tkinter from running mainloop in the background
    root.destroy()

It's not flawless, but I've not been able to find anything better.

Rutkowski answered 18/11, 2023 at 15:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.