本文介绍了tk.mainloop() vs root.mainloop()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一些关于 tk.mainloop()root.mainloop() 使用的问答或文章,但没有成功.

I have tried to find some Q/A or article about the use of tk.mainloop() vs root.mainloop() with no success.

我的问题是:这两种用途之间有什么区别吗?在我看来,正确的方法是使用 tk_instance_variable_name.mainloop() 与仅使用 tk.mainloop() 相比,但从我所见,两者似乎都工作得很好.是否有任何理由需要避免 tk.mainloop() 或者它只是一种偏好.

My question is this: Is there any difference between the 2 uses. It seams to me the correct method would be to use tk_instance_variable_name.mainloop() vs just doing tk.mainloop() but from what I can see both appear to work just fine. Is there any reason one would need to avoid tk.mainloop() or is it just a preference.

如果之前有人问过这个问题,请提供 Q/A 链接,因为我无法找到它.我觉得已经有人问过了,但没有运气搜索它.

If this has been asked before please provide the Q/A link as I cannot seam to find it. I feel like it would have been asked already but no luck search for it.

有人可以解释为什么 tk.mainloop() 在我觉得它不应该工作时会在这里工作,因为它没有用于 tk 实例变量名称.

Can someone maybe explain why tk.mainloop() will work here when I feel like it should not work as it is not being used on the tk instance variable name.

使用 root 的示例按预期工作:

Example using root work just as expected:

import tkinter as tk

root = tk.Tk()
tk.Label(root, text="Test").pack()
root.mainloop() # using the variable name root

就我所知,使用 tk 的示例工作正常:

Example using tk works fine as well as far as I can tell:

import tkinter as tk

root = tk.Tk()
tk.Label(root, text="Test").pack()
tk.mainloop() # using tk

推荐答案

我的问题是:这两种用途之间有什么区别吗.

My question is this: Is there any difference between the 2 uses.

简短回答:在正常用例中没有区别.

Short answer: there is no difference in the normal use case.

每个小部件都有一个关联的 tcl 解释器,它是在创建根小部件时创建的,无论是显式还是隐式.当您从任何小部件调用 mainloop 时,它将在与该小部件的根窗口关联的解释器中运行 mainloop 函数.

Every widget has an associated tcl interpreter that is created when a root widget is created, whether either explicitly or implicitly. When you call mainloop from any widget, it will run the mainloop function in the interpreter associated with the root window of that widget.

如果您调用 tkinter 模块中的 mainloop 方法(例如:tk.mainloop() 在您的示例中),它将调用默认解释器的 mainloop 函数.默认解释器是创建的第一个解释器.因此,在 Tk 的单个实例的正常情况下,tk.mainloop()root.mainloop() 调用完全相同的代码.

If you call the mainloop method that is part of the tkinter module (eg: tk.mainloop() in your example), it will call the mainloop function of the default interpreter. The default interpreter is the first interpreter that was created. Thus, in the normal case of a single instance of Tk, tk.mainloop() and root.mainloop() call the exact same code.

这篇关于tk.mainloop() vs root.mainloop()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 08:42