Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (280 points)

Program :

import tkinter as tk

b = "hi"

print(b)

b1 = tk.StringVar()

b1.set("Hi")

print(b1)

This is the output I'm getting :

hi ##(Output from first print function) 

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

My question is, I just need to know the difference between b and b1 in the above code and I just need to know why a1 is giving me an error?

1 Answer

0 votes
by (26.4k points)
edited by

Basically, the StringVar() method is used for editing a widget's text

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

Here, We will be having an output with a label saying First time

Note:-

We have to use textvariable when we are using string variables

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

Here you see, This code produces a label saying First Time and also a button to change it to Second Time

See, with the help of a normal variable, we can't achieve this, only tkinter's StringVar() can do this. 

Interested to learn more about Python? Come and join Python Online course

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...