Skip to content

Instantly share code, notes, and snippets.

@insolor
Last active November 17, 2021 14:04
Show Gist options
  • Save insolor/13a592d1812b595a49218e2e9caa41c5 to your computer and use it in GitHub Desktop.
Save insolor/13a592d1812b595a49218e2e9caa41c5 to your computer and use it in GitHub Desktop.
Specify parent of a tkinter widget with a context manager
"""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