Why are the digit values in the tkinter items integers and not strings even when I inserted those values as type string?

the title refers to this problem, I need to get the values under the keyword values of Tkinter TreeView using the method item as in: tree.item(v)['values'][0], v being my selection on the treeview. The method returns an integer, and if the value had zeros befores it just ignores them.

Heres an example of what I mean: I need the value marked in yellow exactly as it is (001) instead of (1). Printing this "tree.item(v)['values'][0]" will say the value it's 1 but the treeview shows the real value 001. How can I get the real value (001)?, Thank you.

I need the value marked in yellow exactly as it is (001) instead of (1)

This is the code:

from tkinter import *
from tkinter import ttk

window = Tk()
window.title('Treeview')
window.configure(background='Yellow Green')

ttk.Label(window, text='There must be colors at some rows:', 
    font=('DejaVu Sans', 11, 'bold'), background= 'yellow green').grid(row=0, column=0)
tree = ttk.Treeview(window, columns=('name', 'surname', 'telephone'))
tree.grid(row=1, column=0)
tree.heading('#0', text='Α/Α')
tree.heading('name', text='Name')
tree.heading('surname', text='Surname')
tree.heading('telephone', text='Telephone')
tree.insert('', 0, text='0001', values=("001",2230310,"Hello"))
c = tree.get_children()
print(tree.get_children())
for v in c:
    print(tree.item(v))
    print(tree.item(v)['text'])
    print(tree.item(v)['values'][0], type(tree.item(v)['values'][0]))
application = (window)
window.mainloop()

original code: https://bbs.archlinux.org/viewtopic.php?id=242442

Upvotes: 1

Views: 1003

Answers (1)

Jason Yang
Jason Yang

Reputation: 13057

It looks like tkinter.ttk.Treeview always convert all items in values into integer if possible.

Two related issues,

From ttk code, there's no way to stop the conversion by setting any options for it.

So hack code here, it may work for you. Place code after you import ttk and before your use ttk.Treeview.

from tkinter import *
from tkinter import ttk

def _convert_stringval(value):
    """Converts a value to, hopefully, a more appropriate Python object."""
    if hasattr(value, 'typename'):
        value = str(value)
        try:
            value = int(value)
        except (ValueError, TypeError):
            pass
    return value

ttk._convert_stringval = _convert_stringval

Note: It may not work if tkinter update something related in the future.

Upvotes: 6

Related Questions