什么时候使用变量类?(BooleanVar, DoubleVar, IntVar, StringVar) [英] When to use Variable classes? (BooleanVar, DoubleVar, IntVar, StringVar)

查看:98
本文介绍了什么时候使用变量类?(BooleanVar, DoubleVar, IntVar, StringVar)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不能将 tkinter.widget.configure(text="our text") 用于所有小部件吗?有什么好处,或者使用的主要目的是什么:

Can't tkinter.widget.configure(text="our text") be used for all widgets? What is the advantage, or the main purpose of using:

var_cls = tkinter.StringVar()
tkinter.widget.configure(textvariable=var_cls)

var_cls 是否可以更容易地在方法/类等之间共享?

Is it that var_cls can be more easily shared among methods/classes etc?

变量类示例:

import tkinter as tk
root = tk.Tk()
var = tk.StringVar(value="This will be on the label.")
tk.Label(root, textvariable=var).pack()
root.mainloop()

没有变量类的示例:

import tkinter as tk
root = tk.Tk()
tk.Label(root, text="This will be on the label.").pack()
root.mainloop()

推荐答案

在 tkinter 应用程序中,StringVar(以及 IntVarBooleanVar> 和 DoubleVar) 很少需要.底层 tcl/tk 解释器为其所有变量提供特殊功能,因此这些包装器的存在是为了利用这些功能.

In a tkinter application, StringVar (as well as IntVar, BooleanVar, and DoubleVar) are very rarely needed. The underlying tcl/tk interpreter provides special features for all of its variables, so these wrappers exist to take advantage of those features.

这些变量的两大优势是:

The two big advantages that these variables have are:

  1. 您可以将一个变量与多个小部件相关联,以便两个或多个小部件始终显示完全相同的信息
  2. 您可以绑定要在值更改时调用的函数.

我的观点是,除非您特别需要这两个功能之一,否则不应使用它们.如果您只需要获取或设置小部件的值,则可以在小部件本身上执行此操作(例如:entry_widget.insert(...)、label_widget.configure(text='...') 等).

My opinion is that you should not use them unless you specifically need one of those two features. If you just need to get or set the value of a widget there are methods to do that on the widget itself (eg: entry_widget.insert(...), label_widget.configure(text='...'), etc).

我觉得它们通过引入需要管理的额外对象来增加开销,除非您利用上述两个功能,否则不会提供任何额外的好处.

I feel that they add overhead by introducing an additional object that needs to be managed, without providing any extra benefit unless you're taking advantage of the two features described above.

这篇关于什么时候使用变量类?(BooleanVar, DoubleVar, IntVar, StringVar)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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