Skip to content
Advertisement

My second StringVar fails to show text, shows blank

I was writing a pixel editor in Tkinter, to practice Tkinter and GUI programming. And I was thinking to add a “bottom frame” to show informations like the current tool, the canvas size, etc. But for some reason, the second defined StringVar doesn’t seems to work, while the first one works just fine. By this, I mean the code runs just fine but the second StringVar doesn’t show anything.

Here is the code, for the bottom frame so far:

# Bottom frame
ttk.Style().configure('Interface.TFrame', background='#dbdbdb')
bottomframe = ttk.Frame(root, style='Interface.TFrame')
bottomframe.grid(column=0, row=2, sticky=(N, S, W, E), pady=4)

# An indicator that shows the current selected tool.
toolname = StringVar()
toolname.set('paint tool')

tool_label = ttk.Label(bottomframe, textvariable=toolname, width=11, background='#dbdbdb', anchor='center')
tool_label.grid(column=0, row=0, sticky=(W, E), padx=2)

# A thin separator.
ttk.Separator(bottomframe, orient=VERTICAL).grid(column=1, row=0, sticky=(N, S, W, E))

# An indicator that shows the canvas size.
cvsize = StringVar()
cvsize.set('50x50 px')

cv_size_label = ttk.Label(bottomframe, textvariable=cvsize, width=11, background='#dbdbdb', anchor='center')
cv_size_label.grid(column=2, row=0, sticky=W, padx=2)

So, why it’s not working? The first and the second indicator look nearly same (except the bind operation) and the second one still fails. I also tried removing the first, but it also failed.

I have no idea how can I fix it. I think, I am either missing something and using the StringVar wrong, or there is something in my code that causes this behavior.

So, how can I fix it? And also, why it’s happening?

EDIT: Removed the function definiton part. It wasn’t really part of the question.

Advertisement

Answer

So, I finally understood the reason behind this behavior, thanks to @BryanOakley. Python was removing those unusued variables to free up memory. Because even though they are used in tkinter window, it doesn’t really matter for Python, since the mainloop() is what organizing the window. So, it is necessary to save a reference of the variable somewhere, to prevent Python from removing it. And the easiest way of doing this, is saving the variable with self. Which won’t get removed even after the class definiton ends.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement