Last active
November 17, 2021 14:04
-
-
Save insolor/13a592d1812b595a49218e2e9caa41c5 to your computer and use it in GitHub Desktop.
Specify parent of a tkinter widget with a context manager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Specify parent of a tkinter widget | |
with a context manager""" | |
import tkinter as tk | |
from contextlib import contextmanager | |
@contextmanager | |
def set_parent(new_parent): | |
old_root = tk._default_root | |
tk._default_root = new_parent | |
try: | |
yield new_parent | |
finally: | |
tk._default_root = old_root | |
def on_button_press(): | |
with set_parent(tk.Toplevel()) as child: | |
tk.Label(text="In the child window").pack() | |
child.wait_window() | |
tk.Label(text="In the main window again").pack() | |
root = tk.Tk() | |
tk.Label(text="In the main window").pack() | |
tk.Button(text="Press me", command=on_button_press).pack() | |
root.mainloop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment