Simson
Simson

Reputation: 47

How to add a string that contains whitespace to a Tkinter Treeview column

I use the tree.insert method to insert data into the treeview widget. Under the values option I specify the string variable where to get the data. If the string contains whitespace then the string gets broken up into smaller strings which are placed into a list. How can I add data into the treeview columns without getting it truncated to the first whitespace?

Thank you.

import tkinter as tk
from tkinter import ttk
app = tk.Tk()
tree = ttk.Treeview(app)
tree.grid(row=0, column=0)
tree.config(columns=('Value1'), selectmode='browse')
tree.column('#0', width=150, minwidth=10, stretch=tk.YES)
tree.column('Value1', width=80, minwidth=10, stretch=tk.YES)
tree.heading('#0', text='Name', anchor=tk.W)
tree.heading('Value1', text='Value', anchor=tk.W)
data = [['John', '123456'], ['Mary', '123 456'], ['Edward', 'abcdef'], ['Lisa', 'ab cd ef']]
for item in data:
    print(item[1], type(item[1]))
    tree.insert("", 'end', item[0], text=item[0], values=item[1])
    print(tree.item(item[0])['values'], type(tree.item(item[0])['values']))
app.mainloop()

Upvotes: 2

Views: 3140

Answers (3)

Oliver Dixon
Oliver Dixon

Reputation: 11

Of the two answers given here, I tend to disagree with setting values=item[1] to values=(item[1]) since I still had an issue with Treeview splitting around spaces.

I tried the escaping solution and that worked perfectly. I'd take it a little further if I may and change your values=(item[1]) to values=(item[1].replace(" ", "\ ")) so your line would read::

tree.insert("", 'end', item[0], text=item[0], values=(item[1].replace(" ", "\ "))

...just as a catch all

Upvotes: 1

Er. Harsh Rathore
Er. Harsh Rathore

Reputation: 798

Its not a big task just give a backslash before a white-space, like :-

data = [['John', '123456'], ['Mary', '123\ 456'], ['Edward', 'abcdef'], ['Lisa', 'ab\ cd\ ef']]

It will show you the white-spaces in your GUI because '123\ 456' will treated as a single element in type 'list'.

Upvotes: 2

Henry Yik
Henry Yik

Reputation: 22493

values expects an iterable, so when you pass a string to it, it will tend to do weird things. Easiest way to fix it in your code is to pass it as a tuple:

tree.insert("", 'end', item[0], text=item[0], values=(item[1],))

Upvotes: 6

Related Questions