Tkinter Treeview字符串显示不全及选中值异常问题求助
Tkinter Treeview 显示不全与取值异常问题解决
问题1:如何确保插入的字符串完整显示?
你的代码存在两个导致显示不全的问题:
- 列宽未设置且
stretch="no"限制了列的拉伸,默认列宽不足以容纳长文件路径; - 列定义时
('File path')不是标准元组格式(缺少末尾逗号),虽不影响功能,但不符合Treeview的规范要求。
修复方案:
- 为
tree.column设置足够的初始宽度,并允许列随窗口拉伸(可选):
将tree.column("#1", stretch="no")修改为:tree.column("#1", width=500, stretch="yes", anchor="w")width=500设置初始列宽为500像素(可根据最长路径调整);stretch="yes"让列宽随窗口大小自动调整;anchor="w"保证文本左对齐,避免右侧内容被截断。
- 规范列定义为元组:
tree['columns'] = ('File path',)(添加末尾逗号,确保是元组类型)。
问题2:选中行回车后如何获取原字符串?
问题出在tree.insert的values参数:你传入的是单个字符串,Treeview会将其视为可迭代对象,拆分成单个字符作为列值,导致获取到的是字符序列而非原路径。
修复方案:
- 插入数据时,将
values参数改为元组格式,即使只有一列也要加末尾逗号,示例:tree.insert("", "end", values=("C:/Users/PB/PyProjects/VA_PY_36/Python Excel project/people 1.xlsx",)) - 在
select函数中,通过tree.item(x)['values'][0]即可获取完整的原路径字符串。
修复后的完整代码
import tkinter as tk import tkinter.ttk selected_from_list = [] def select(): curItems = tree.selection() # 清空之前的选中记录(避免重复添加) selected_from_list.clear() for x in curItems: # 获取原路径字符串 file_path = tree.item(x)['values'][0] selected_from_list.append(file_path) print(file_path) print("选中的路径列表:", selected_from_list) # 销毁之前的标签,避免重复显示 for widget in root.winfo_children(): if isinstance(widget, tk.Label) and widget != tree: widget.destroy() tk.Label(root, text="\n".join(selected_from_list)).pack() root = tk.Tk() tree = tkinter.ttk.Treeview(root, height=4) tree['show'] = 'headings' # 规范列定义为元组 tree['columns'] = ('File path',) tree.heading("#1", text='Badge Name', anchor='w') # 设置列宽并允许拉伸 tree.column("#1", width=500, stretch="yes", anchor="w") tree.pack() # 插入时使用元组传值 tree.insert("", "end", values=("C:/Users/PB/PyProjects/VA_PY_36/Python Excel project/people 1.xlsx",)) tree.insert("", "end", values=("C:/Users/PB/PyProjects/VA_PY_36/Python Excel project/people 2.xlsx",)) tree.insert("", "end", values=("C:/Users/PB/PyProjects/VA_PY_36/Python Excel project/people 3.xlsx",)) tree.bind("<Return>", lambda e: select()) root.mainloop()
内容的提问来源于stack exchange,提问作者Zerahny Chew
相关产品推荐
相关产品推荐

