tkinter 的 Tk 和 Toplevel 类有什么区别? [英] What's the difference between tkinter's Tk and Toplevel classes?

查看:47
本文介绍了tkinter 的 Tk 和 Toplevel 类有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 3 中,我从交互式 shell 运行以下命令:

<预><代码>>>>导入 tkinter>>>类型(tkinter.Tk())<类'tkinter.Tk'>>>>类型(tkinter.Toplevel())<class 'tkinter.Toplevel'>

这两者都创建了单独的窗口.我假设 tkinter.Tk() 返回 tkinter 应用程序的主"窗口,而任何其他窗口都应该使用 tkinter.Toplevel() 创建.

我注意到如果你关闭 tkinter.Tk() 的窗口,两个窗口都会关闭.此外,如果您调用 tkinter.Toplevel() 而不调用 tkinter.Tk(),则会创建两个窗口(其中一个是主"窗口,关闭时,也会关闭顶层窗口).

这准确吗?我还应该关注其他任何差异吗?

解决方案

你的总结是准确的.tkinter 的核心架构特性之一是小部件存在于具有恰好一个根窗口的层次结构中.当您实例化 Tk 时,您将获得该根窗口.

实例化 Tk 不仅仅是创建一个窗口,它还初始化整个 tkinter 框架.它实际上启动了一个隐藏的 tcl 解释器,它执行管理小部件的实际工作.Tkinter 只是一个围绕这个解释器的 python 包装器.

如果您尝试创建其他小部件而没有先明确创建根窗口,则会自动创建一个,因为每个 tkinter 应用程序都必须恰好有一个根窗口.

In Python 3, I run the following from the interactive shell:

>>> import tkinter
>>> type(tkinter.Tk())
<class 'tkinter.Tk'>
>>> type(tkinter.Toplevel())
<class 'tkinter.Toplevel'>

Both of these create individual windows. I assume that tkinter.Tk() returns the "main" window of the tkinter app, while any additional windows should be created with tkinter.Toplevel().

I noted that if you close tkinter.Tk()'s window, both windows close. Also, if you call tkinter.Toplevel() without a call to tkinter.Tk(), two windows are created (one of them being the "main" window that, when closed, will also close the Toplevel window).

Is this accurate? Are there any other differences that I should be concerned with?

解决方案

Your summary is accurate. One of tkinter's core architectural features is that the widgets exist in a hierarchy with exactly one root window. That root window is what you get when you instantiate Tk.

Instantiating Tk does more than create a window, it initializes the entire tkinter framework. It actually starts up a hidden tcl interpreter which does the actual work of managing widgets. Tkinter is just a python wrapper around this interpreter.

If you attempt to create some other widget without explicitly creating a root window first, one will be created automatically since every tkinter application must have exactly one root window.

这篇关于tkinter 的 Tk 和 Toplevel 类有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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