Warm tip: This article is reproduced from stackoverflow.com, please click
python tcl tk tkinter

Why are multiple instances of Tk discouraged?

发布于 2020-05-03 15:07:27

Consider below example:

import tkinter as tk

root = tk.Tk()
root.title("root")

other_window = tk.Tk()
other_window.title("other_window")

root.mainloop()

and also see below example that creates instances of Tk back-to-back instead of at once, so there's exactly one instance of Tk at any given time:

import tkinter as tk

def create_window(window_to_be_closed=None):
    if window_to_be_closed:
        window_to_be_closed.destroy()
    window = tk.Tk()
    tk.Button(window, text="Quit", command=lambda arg=window : create_window(arg)).pack()
    window.mainloop()

create_window()
  • Why is it considered bad to have multiple instances of Tk?
  • Is the second snippet considered a bit better, or does it suffer from the same conditions the first code does?
Questioner
Nae
Viewed
27
8,172 2018-01-01 23:15

Why is it considered bad to have multiple instances of Tk?

Tkinter is just a python wrapper around an embedded Tcl interpreter that imports the Tk library. When you create a root window, you create an instance of a Tcl interpreter.

Each Tcl interpreter is an isolated sandbox. An object in one sandbox cannot interact with objects in another. The most common manifestation of that is that a StringVar created in one interpreter is not visible in another. The same goes for widgets -- you can't create widgets in one interpreter that has as a parent widget in another interpreter.

From a technical standpoint, there's no reason why you can't have two instances of Tk at the same time. The recommendation against it is because there's rarely an actual need to have two or more distinct Tcl interpreters, and it causes problems that are hard for beginners to grasp.

Is the second snippet considered a bit better, or does it suffer from the same conditions the first code does?

It's impossible to say whether the second example in the question is better or not without knowing what you're trying to achieve. It probably is no better since, again, there's rarely ever a time when you actually need two instances.

The best solution 99.9% of the time is to create exactly one instance of Tk that you use for the life of your program. Quite simply, that is how tkinter and the underlying Tcl/Tk interpreter was designed to be used.