I am developing a very crude window to broaden my understanding of certain TKinter widgets like comboboxes and scales.
The current widget I am working on is a simple Listbox featuring a list of pages to visit.
I have gotten stuck trying to understand the use of Stringvar to populate the listbox.
I am basing the code off of this snippet from TKDocs:
choices = ["apple", "orange", "banana"]
choicesvar = StringVar(value=choices)
This is my code:
other_frames = ['Cameras', 'Tasks', 'Maintainance', 'Clock', 'Assistance', 'Tools']
StringVar = " "
O_F_var = StringVar(value=other_frames)
I am getting errors on this step and only this step, so I am obviously misunderstanding how to use a stringvar and/or what value to give a stringvar.
I read on the TKDocs website that just like Entry, the Listbox also uses StringVar.
To try and understand, I visited the explanation for the Entry widget. And in the code snippet, the value for StringVar was a nonetype.
TKDocs code snippet:
username = StringVar()
name = ttk.Entry(parent, textvariable=username)
I tried using a Nonetype value for my StringVar and I expected to have the Listbox become populated by the List values since I had "used a StringVar as an intermediary." like the TKDocs tutorial said.
I instead recieved the error:
TypeError: ‘str’ object is not callable
I then tried to figure out why things were not lining up, sadly to no avail.
An explanation and/or resource to help me understand would be appreciated.
>Solution :
StringVar is a class in tkinter. You can’t just use StringVar = " " and expect that to work. You need to create an instance of the StringVar class.
In this case, however, you’re wanting to use a variable for a Listbox, and a listbox works on lists rather than strings. If you use a list as a value for a StringVar, tkinter will convert the list to a string and destroy the fact that it represents a list.
Instead, when using the variable with a Listbox you can use the Variable class, which will preserve the base type of the data.
Example:
import tkinter as tk
choices = ["apple", "orange", "banana"]
root = tk.Tk()
var = tk.Variable(value=choices)
lb = tk.Listbox(root, listvariable=var)
lb.pack(fill="both", expand=True)
root.mainloop()
