0

I am starting to learn Tkinter and have been creating new windows with new instances of Tk every time. I just read that that wasn't a good practice. If so, why? And how could this be done better? I have seen others create windows with Toplevel and Frame instances. What are the benefits/drawbacks of using these instead?

In case this makes a difference: The application that I am writing code for starts off with a login window and then proceeds to a second window is the entered password is correct.

2
  • 1
    This may be a duplicate, but I disagree with 'too broad'. There is a very short answer. Code that works until it doesn't, for mysterious reasons, because it has subtle bugs, is a damn nuisance. (Based on experience with unintended duplicate Tk instances.) Bryan has it exactly right. Commented May 28, 2016 at 22:07
  • I agree, this isn't true broad. There is only one true answer. Commented May 29, 2016 at 0:59

1 Answer 1

3

Every tkinter program needs exactly one instance of Tk. Tkinter is a wrapper around an embedded tcl interpreter. Each instance of Tk gets its own copy of the interpreter, so two Tk instances have two different namespaces.

If you need multiple windows, create one instance of Tk and then additional windows should be instances of Toplevel.

While you can create, destroy, and recreate a root window, there's really no point. Instead, create the root window for the login screen, and then just delete the login screen widgets and replace them with your second window.

This becomes trivial if you make each of your "windows" a separate class that inherits from tk.Frame. Because tkinter will destroy all child widgets when a frame is destroyed, it's easy to switch from one "window" to another. Create an instance of LoginFrame and pack it in the root window. When they've input a correct password, destroy that instance, create an instance of MainWindow and pack that.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! So definitely use Toplevel instances over Frame instances? How is Frame different (when I try it out, I can create windows with both...)
@Jonas: if you want a separate window, your only choice is Toplevel. A Frame can only exist inside other windows.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.