如何在Python的Tkinter Treeview中获取带前导零的列值
解决Treeview读取带前导零字符串丢失前导零的问题
问题根源在于ttk Treeview会自动将看起来是纯数字的字符串转换为数值类型,导致前导零被丢弃。以下是两种可行的解决方法:
方法一:添加零宽空格阻止类型转换
在插入带前导零的字符串时,末尾追加一个零宽空格(\u200b),这个字符不会在界面显示,但会让Treeview将其识别为非纯数字字符串,从而保留原始格式。读取时再移除这个零宽空格即可。
修改后的代码:
import tkinter as tk from tkinter import ttk root = tk.Tk() root.title("Treeview Example") # build a Treeviews tree = ttk.Treeview(root) tree.pack(fill="both", expand=True) tree["columns"] = ("name", "age", "phone") tree.heading("#0", text="ID", anchor=tk.W) tree.heading("name", text="Name", anchor=tk.W) tree.heading("age", text="Age", anchor=tk.W) tree.heading("phone", text="Phone", anchor=tk.W) # 插入时给手机号添加零宽空格 tree.insert("", tk.END, text="001", values=("Max ", "30", "0011223344\u200b")) # read data from Treeview child = tree.get_children() if child: tree.focus(child[0]) tree.selection_set(child[0]) item = tree.item(tree.focus()) values = item["values"] for value in values: # 读取时移除零宽空格 raw_value = str(value).replace("\u200b", "") print(raw_value) # 正确结果:"0011223344" root.mainloop()
方法二:利用Treeview的item属性存储原始值
插入数据后,将原始字符串单独存储到Treeview的item自定义属性中,读取时直接获取这个存储的值:
修改后的代码:
import tkinter as tk from tkinter import ttk root = tk.Tk() root.title("Treeview Example") # build a Treeviews tree = ttk.Treeview(root) tree.pack(fill="both", expand=True) tree["columns"] = ("name", "age", "phone") tree.heading("#0", text="ID", anchor=tk.W) tree.heading("name", text="Name", anchor=tk.W) tree.heading("age", text="Age", anchor=tk.W) tree.heading("phone", text="Phone", anchor=tk.W) # 插入数据并获取item的iid item_id = tree.insert("", tk.END, text="001", values=("Max ", "30", "0011223344")) # 将原始手机号存储到item的自定义属性中 tree.item(item_id, phone_raw="0011223344") # read data from Treeview child = tree.get_children() if child: tree.focus(child[0]) tree.selection_set(child[0]) item = tree.item(tree.focus()) # 直接读取存储的原始值 print(item["phone_raw"]) # 正确结果:"0011223344"
两种方法中,方法一更简便,不需要额外存储逻辑,且界面显示不受影响。
内容的提问来源于stack exchange,提问作者Didi
相关产品推荐
相关产品推荐

