Why is Toplevel showing 2 windows?
Asked Answered
C

1

2

I am trying to make a tkinter application which doesn't close everything (other windows) when the first window (root) is closed. I have tried to use Toplevel() which works perfectly for pop-up windows in other programs but not for making a base level.

from tkinter import *

top = Toplevel(bg='red')

top.mainloop()

I don't know if this is possible or I don't know if I can change the Tk()'s properties to make it so it doesn't shut all other windows down.

Capstone answered 16/1, 2018 at 20:19 Comment(4)
You don't use a Toplevel as root only Tk. Toplevel is not a root, but always a 'dialog' for a root window (Tk).Knuckleduster
to create main window use Tk(). Toplevel() is used to create second window (subwindow/dialog/messagebox/etc.)Terpsichorean
https://mcmap.net/q/247131/-extra-tkinter-gui-popup/7032856Megaspore
You simply must have a root window. If you don't create one, tkinter will create one for you.Wakashan
M
5

There are two windows getting displayed because when a tkinter widget is created, it forces a Tk instance to be created as well, and every widget, unless a parent is explicitly passed, is a child to that automatically created Tk instance. So your code essentially mimics the following code:

from tkinter import *

root = Tk()

top = Toplevel(root, bg='red')

root.mainloop()

Now there are some ways to work around that for the behavior you want, one is to hide the actual Tk instance:

import tkinter as tk

root = tk.Tk()
root.withdraw()

top = tk.Toplevel(root, bg='red')

#to display root window again
#root.iconify()
#root.deiconify()
root.mainloop()

Another way would be to overrule the deletion of the root itself, but I doubt that's actually what you want:

import tkinter as tk


def callback():
    print("Won't close")

root = tk.Tk()

root.protocol("WM_DELETE_WINDOW", callback)

root.mainloop()
Megaspore answered 16/1, 2018 at 20:30 Comment(1)
Withdrawing the root works as I would like, thanks a lotCapstone

© 2022 - 2024 — McMap. All rights reserved.