在我正在处理的项目中,您可以编辑treeview表单中显示的数据内容。其中一个数据字段是一个始终以0开头的电话号码。
在表格中选择正确的记录并使用tree.item(tree.selection())
从中提取数据时。由于某种原因,电话号码会自动转换为整数,因此当它们在框中显示给用户时,它们会在开头时丢失0。
有什么方法可以解决这个问题吗?
from tkinter import *
import tkinter.ttk as ttk
def fnEdit(tree):
items = tree.item(tree.selection())
print(items['values'][0])
myGui = Tk()
container = Frame(myGui)
container.pack(expand=True, fill="both")
editButton = Button(myGui, text='Edit', command=lambda: fnEdit(tree))
editButton.pack(fill="x")
table_header = ['Contact No.']
tree = ttk.Treeview(container, columns=table_header, show="headings")
tree.column(table_header[0])
tree.insert('', 'end', values='01234567895')
tree.pack(expand=True, fill="both")
myGui.mainloop()
答案 0 :(得分:1)
将数据从values
复制到text
(向树中添加新项时),然后从text
读取(而不是values
}),将允许克服这种限制。
from tkinter import Tk
from tkinter import Frame
from tkinter import Button
import tkinter.ttk as ttk
# print(TkVersion)
# 8.6
def edit(tree):
if len(tree.selection()) == 1:
selected_item = tree.item(tree.selection())
#print(selected_item['values'][0])
print(selected_item['text'])
else:
print('please select item')
gui = Tk()
container = Frame(gui)
container.pack(expand=True, fill='both')
edit_button = Button(gui, text='Edit', command=lambda: edit(tree))
edit_button.pack(fill='x')
tree = ttk.Treeview(container, show='headings')
col_names = ['Contact No.']
tree['columns'] = col_names
for col_name in col_names:
tree.heading(col_name, text=col_name)
phone_nums = ['01234567895']
for phone_num in phone_nums:
tree.insert('', 'end', text=phone_num, values=phone_num)
tree.pack(expand=True, fill='both')
gui.mainloop()