import tkinter as tk
a = "hi"
print(a)
a1 = tk.StringVar()
a1.set("Hi")
print(a1)
hi ##(Output from first print function)
AttributeError: 'NoneType' object has no attribute '_root' (Output from second print function)
What is the difference between a
and a1
in above code and their use-cases. Why a1
is giving error?
StringVar is a class that provides helper functions for directly creating and accessing such variables in that interpreter. As such, it requires that the interpreter exists before you can create an instance. This interpreter is created when you create an instance of Tk .
In the case of textvariable , which is mostly used with Entry and Label widgets, it is a variable that will be displayed as text. When the variable changes, the text of the widget changes as well.
_ClassType IntVarConstruct an integer variable. set(self, value) Set the variable to value, converting booleans to integers. get(self) Return the value of the variable as an integer.
A StringVar() is used to edit a widget's text
For example:
import tkinter as tk
root = tk.Tk()
my_string_var = tk.StringVar()
my_string_var.set('First Time')
tk.Label(root, textvariable=my_string_var).grid()
root.mainloop()
Will have an output with a label saying First Time
NOTE:textvariable
has to be used when using string variables
And this code:
import tkinter as tk
def change():
my_string_var.set('Second Time')
root = tk.Tk()
my_string_var = tk.StringVar()
my_string_var.set('First Time')
tk.Label(root, textvariable=my_string_var).grid()
tk.Button(root, text='Change', command=change).grid(row=1)
root.mainloop()
Produces a label saying First Time
and a button to very easily change it to Second Time
.
A normal variable can't do this, only tkinter's StringVar()
Hopes this answers your questions!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With