Hide or close top level window when main window isn't visible
Question:
Is there a way to close or preferably hide a top-level window if the main window is not visible?
I was already able to do that by checking if the minimize button had been clicked. Still, there are several ways to "minimise" a window such as going into another tab, hitting the side of the taskbar (on windows) etc…
Thanks!
Answers:
You can try binding functions to <Unmap>
and <Map>
events of the window. Like below:
from tkinter import *
root = Tk()
root.geometry("600x300")
for _ in range(3):
Toplevel(root)
def hide_all(event):
# You could also call each child directly if you have the object but since we aren't tracking
# the toplevels we need to loop throught the children
for child in root.children.values():
if isinstance(child, Toplevel):
child.withdraw() # or depending on the os: 'child.wm_withdraw()'
def show_all(event):
# You could also call each child directly if you have the object but since we aren't tracking
# the toplevels we need to loop throught the children
for child in root.children.values():
if isinstance(child, Toplevel):
child.deiconify() # or depending on the os: 'child.wm_deiconify()'
root.bind("<Unmap>", hide_all) # Fires whenever 'root' is minimzed
root.bind("<Map>", show_all) # Fires whenever 'root' is restored and shown
root.mainloop()
If this isn’t what you want, you may be able to use the <Expose>
or <Visibility>
events to get what you want. Link to all tkinter events: tkinter events from anzeljg
Is there a way to close or preferably hide a top-level window if the main window is not visible?
I was already able to do that by checking if the minimize button had been clicked. Still, there are several ways to "minimise" a window such as going into another tab, hitting the side of the taskbar (on windows) etc…
Thanks!
You can try binding functions to <Unmap>
and <Map>
events of the window. Like below:
from tkinter import *
root = Tk()
root.geometry("600x300")
for _ in range(3):
Toplevel(root)
def hide_all(event):
# You could also call each child directly if you have the object but since we aren't tracking
# the toplevels we need to loop throught the children
for child in root.children.values():
if isinstance(child, Toplevel):
child.withdraw() # or depending on the os: 'child.wm_withdraw()'
def show_all(event):
# You could also call each child directly if you have the object but since we aren't tracking
# the toplevels we need to loop throught the children
for child in root.children.values():
if isinstance(child, Toplevel):
child.deiconify() # or depending on the os: 'child.wm_deiconify()'
root.bind("<Unmap>", hide_all) # Fires whenever 'root' is minimzed
root.bind("<Map>", show_all) # Fires whenever 'root' is restored and shown
root.mainloop()
If this isn’t what you want, you may be able to use the <Expose>
or <Visibility>
events to get what you want. Link to all tkinter events: tkinter events from anzeljg