【问题标题】:How to insert a dictionary value into Tkinter Treeview如何将字典值插入 Tkinter Treeview
【发布时间】:2018-03-21 15:46:31
【问题描述】:

我正在开发一个程序来解码 CAN 总线错误消息。这些消息被准确地读入字典,但我很难让它们显示在树视图中。我已经阅读了插入方法并查找了无数示例,但字典和树视图的混合让我感到困惑。这是一个小测试程序,我在插入语句中做错了什么?

from tkinter import *
from collections import OrderedDict
from tkinter import filedialog, ttk

GuiWindow = Tk()

TestDict = OrderedDict()

TestDict["MsgID"] = 1
TestDict["OtherData"] = 2

Errortree = ttk.Treeview(
    GuiWindow,
    columns=('Message ID', 'Other Data'))
Errortree.heading('#0', text='Message ID')
Errortree.heading('#1', text='Other Data')
Errortree.column('#0', stretch=YES)
Errortree.column('#1', stretch=YES)


treeview = Errortree

def TreeInsert():
print(TestDict)

Errortree.insert("", 'end', TestDict['MsgID'], TestDict['OtherData'])

scanvar = BooleanVar()

scanbtn = Checkbutton(
    GuiWindow,
    text="scan",
    variable=scanvar,
    command=TreeInsert,
    indicatoron=0)

Errortree.grid(row=0, columnspan=5, sticky='nsew')

scanbtn.grid(row=1, column=0)

GuiWindow.geometry('{}x{}'.format(400, 300))
GuiWindow.mainloop()

我确实意识到我有一个双重导入,但为了可验证的示例,它是为了让我摆脱 pylint。

【问题讨论】:

    标签: python tkinter treeview can-bus


    【解决方案1】:

    替换这部分代码

    Errortree.insert("", 'end', TestDict['MsgID'], TestDict['OtherData'])
    

    有了这个

    Errortree.insert("", 'end', values=(TestDict['MsgID'], TestDict['OtherData']))
    

    您需要将您的数据作为tuple 插入treeview,所以我将您的dic 值转换为tuple

    Errortree.insert("", 'end', values=(TestDict['MsgID'], TestDict['OtherData']))

    完整代码

    from tkinter import *
    from collections import OrderedDict
    from tkinter import filedialog, ttk
    
    GuiWindow = Tk()
    
    TestDict = OrderedDict()
    
    TestDict["MsgID"] = 1
    TestDict["OtherData"] = 2
    
    Errortree = ttk.Treeview(GuiWindow,columns=('Message ID', 'Other Data'),show="headings")
    Errortree.heading('#1', text='Message ID')
    Errortree.heading('#2', text='Other Data')
    Errortree.column('#1', stretch=YES)
    Errortree.column('#2', stretch=YES)
    
    
    
    
    def TreeInsert():
    
        print(TestDict)
    
    #Errortree.insert("", 'end', TestDict['MsgID'], TestDict['OtherData'])
    Errortree.insert("", 'end', values=(TestDict['MsgID'], TestDict['OtherData']))
    
    scanvar = BooleanVar()
    
    scanbtn = Checkbutton( GuiWindow,text="scan",variable=scanvar,
    command=TreeInsert,indicatoron=0)
    
    Errortree.grid(row=0, columnspan=5, sticky='nsew')
    
    scanbtn.grid(row=1, column=0)
    
    GuiWindow.geometry('{}x{}'.format(400, 300))
    GuiWindow.mainloop()
    

    【讨论】:

    猜你喜欢
    • 2021-09-28
    • 2021-04-23
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    • 2014-08-24
    • 1970-01-01
    相关资源
    最近更新 更多