I have a tkinter Listbox and I'm using a StringVar().set() to set the values from a list. When I get the values back using StringVar().get(), they are converted to an awkward string format, like this:
"('Item1', 'Item2', 'Item3')"
What's the best way to avoid this conversion in the first place, or failing that, to convert the string back to the initial list?
You can use this snippet of code to reproduce the problem in its most simple form:
import tkinter as tk
root = tk.Tk()
values = tk.StringVar(root)
values.set(['Item1', 'Item2','Item3'])
print(values.get())
It's not pretty, but I had come up with this:
values.get()[2:-2].split("', '")
ast.literal_evaland the docs state that If you call the .get() method of the listvariable, you will get back a string of the form "('v0', 'v1', ...)", where each vi is the contents of one line of the listbox. which probably means that there is not really any built-in way to achieve it but rather have to use your own method orast.literal_evalstras a variable name, it is a built-in Python functionStringVar(seeStringin its name) so what did you expect, also the pattern doesn't change so using the other method would work too but it just doesn't look as good (also need to account for the extra') and also see comment below which solves this without efforttk.Variableinstead oftk.StringVar.