3

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()
Nae
  • 14,209
  • 7
  • 52
  • 79
  • 1
    you can assign the same `StringVar` to `Label` and `Entry` and when you change text in `Entry` then it changes text in `Label` automatically. – furas Nov 16 '17 at 17:06

3 Answers3

11

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.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
1

StringVar can be bound to a widget, so you just need to have a handle on the StringVar and you can modify its value and it will update automatically. Otherwise, you would need to keep a handle on the widget itself and handle the event loop stuff etc. Basically you should use StringVar etc. when the value could change. If it's going to be static for certain, you don't need it.

Nae
  • 14,209
  • 7
  • 52
  • 79
  • Well, to be fair, you either have to keep a handle to the widget, or a handle to the variable. In both cases, you have to keep and handle and call a function in order to update the value. – Bryan Oakley Nov 16 '17 at 17:04
0

StringVar is very useful for updating eg. a Label whenever the value changes. You can extract its content and convert to float/integer and later on use in calculations. It can be also updated with .set method and then there's no need to have the value updated in the window/other container as it happens automatically. While conversion to "understandable" variable type presents some difficulty, it is still worth it.