Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

python - When to use Variable classes? (BooleanVar, DoubleVar, IntVar, StringVar)

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)

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


Example with a Variable class:

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()

Example without a Variable class:

import tkinter as tk
root = tk.Tk()
tk.Label(root, text="This will be on the label.").pack()
root.mainloop()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. You can associate one variable with more than one widget, so that two or more widgets display exactly the same information all the time
  2. You can bind functions to be called when the values change.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...