1

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("', '")
6
  • you could use ast.literal_eval and 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 or ast.literal_eval Commented Nov 1, 2021 at 22:42
  • also don't use str as a variable name, it is a built-in Python function Commented Nov 1, 2021 at 22:48
  • I mean it is a StringVar (see String in 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 effort Commented Nov 1, 2021 at 22:51
  • 3
    Use tk.Variable instead of tk.StringVar. Commented Nov 1, 2021 at 22:51
  • @acw1668 - thank you, that works like a dream. Perhaps write a couple of lines as an answer? Commented Nov 1, 2021 at 23:00

1 Answer 1

2

As StringVar is inherited from Variable with overridden get() function which converts the stored value to string.

Using Variable will not have such conversion.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.