Tkinter 创建多个窗口 - 使用新的 Tk 实例还是顶层或框架? [英] Tkinter Creating Multiple Windows - Use new Tk instance or Toplevel or Frame?

查看:27
本文介绍了Tkinter 创建多个窗口 - 使用新的 Tk 实例还是顶层或框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习 Tkinter,并且每次都使用 Tk 的新实例创建新窗口.我刚刚读到这不是一个好习惯.如果是这样,为什么?怎样才能做得更好?我见过其他人使用 Toplevel 和 Frame 实例创建窗口.使用它们有什么好处/缺点?

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.

推荐答案

每个 tkinter 程序都需要一个 Tk 实例.Tkinter 是嵌入式 tcl 解释器的包装器.Tk 的每个实例都有自己的解释器副本,所以两个 Tk 实例有两个不同的命名空间.

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.

如果你需要多个窗口,创建一个Tk的实例,然后额外的窗口应该是Toplevel的实例.

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.

如果您使每个窗口"成为继承自 tk.Frame 的单独类,这将变得微不足道.由于 tkinter 会在销毁框架时销毁所有子部件,因此很容易从一个窗口"切换到另一个窗口".创建一个 LoginFrame 的实例并将其打包到根窗口中.当他们输入正确的密码时,销毁该实例,创建 MainWindow 的实例并打包.

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.

这篇关于Tkinter 创建多个窗口 - 使用新的 Tk 实例还是顶层或框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆