0

I created a .py script that autofill some forms using Selenium. In the start of the code, I used Tkinter extension to use the messagebox and filedialog function.

My code runs fine, but everytime I got an annoying window called "tk" (I guess it is related to Tkinter). This window is blank, but I would like to remove it from my code run.

Is there a way to do this?

enter image description here

1
  • 1
    First create a tkinter.Tk() then call <tkinter.Tk>.withdraw() to hide the window. When you are done with the filedialog, call <tkinter.Tk>.destroy() to destroy the window Commented May 6, 2021 at 18:54

1 Answer 1

2

Try this:

import tkinter as tk
from tkinter import filedialog

# Create a dummy window
root = tk.Tk()
# Hide the window
root.withdraw()

# Use `filedialog` freely
print(filedialog.askopenfilename())

# If you want to destroy the window at the end.
# You don't have to
root.destroy()

The reason why that window appears is linked to how tkinter handles new windows. It uses tkinter.Toplevel instead of a tkinter.Tk. But a tkinter.Toplevel can't exist without a tkinter.Tk so it creates one. That is the window that you see.

To hide the window you have to first create your own tkinter.Tk and hide it using <tkinter.Tk>.withdraw().

Sign up to request clarification or add additional context in comments.

9 Comments

In single lines: tk.Tk().withdraw() and then the rest
It does not, but that does not matter. Because a reference does not have to be stored here. Just the tcl interpreter have to be created explicitly, so as to just hide it out.
You don't have to call root.destroy() it automatically destroys when the window is destroyed.
@CoolCloud I am assuming that OP has a lot of code that follows the filedialog. Also anyone looking at this in the future, it would be better if I provide code with best practises.
I agree, it's best to explictly create a root window, and to keep a reference to it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.