【问题标题】:Selection from a Treeview automatically converts string numbers to integers从树视图中选择会自动将字符串数字转换为整数
【发布时间】:2017-07-30 19:55:11
【问题描述】:

在我正在处理的项目中,您可以编辑以树形视图形式显示的数据内容。数据字段之一是始终以 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()

【问题讨论】:

  • 我不确定为什么会发生这种情况(但似乎每次字符串也可以解释为数字时都会发生),但是您有一个笨拙的解决方法:您可以将返回的整数转换为字符串并在前面加上必要的零。
  • @nbro 这就是我认为我可以绕过它的方式。不太确定考试委员会会怎么想,但这可能是我唯一的选择。
  • 这似乎与 stackoverflow.com/q/39067164/7432 重复。不幸的是,这似乎是 ttk 中的一个错误。

标签: python string tkinter treeview selection


【解决方案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()

【讨论】:

    猜你喜欢
    • 2014-09-05
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 2013-07-19
    • 1970-01-01
    • 2012-02-21
    相关资源
    最近更新 更多