如何将包含空格的字符串添加到 Tkinter Treeview 列 [英] How to add a string that contains whitespace to a Tkinter Treeview column

查看:35
本文介绍了如何将包含空格的字符串添加到 Tkinter Treeview 列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 tree.insert 方法将数据插入到 treeview 小部件中.在 values 选项下,我指定了获取数据的字符串变量.如果字符串包含空格,则该字符串会被分解成更小的字符串,然后放入一个列表中.如何将数据添加到树视图列中而不将其截断为第一个空格?

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?

谢谢.

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()

推荐答案

values 期望一个可迭代的,所以当你传递一个 string 给它时,它会倾向于这样做奇怪的事情.在代码中修复它的最简单方法是将其作为元组传递:

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],))

这篇关于如何将包含空格的字符串添加到 Tkinter Treeview 列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆