Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between a variable and StringVar() of tkinter

Code:

import tkinter as tk
a = "hi"
print(a)
a1 = tk.StringVar()
a1.set("Hi")
print(a1)

Output:

hi ##(Output from first print function) 

AttributeError: 'NoneType' object has no attribute '_root' (Output from second print function) 

My question:

What is the difference between a and a1 in above code and their use-cases. Why a1 is giving error?

like image 926
Msquare Avatar asked Aug 10 '18 09:08

Msquare


People also ask

What is StringVar () in Tkinter?

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 .

What does text variable do in Tkinter?

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.

What is IntVar () in Tkinter?

_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.


1 Answers

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!

like image 96
BeastCoder Avatar answered Oct 02 '22 17:10

BeastCoder