如何在Tkinter Treevi中插入字典值

2024-06-16 10:52:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个程序来解码can总线错误信息。这些信息被准确地读入字典,但我在树状视图中显示它们时遇到了困难。我读过insert方法并查找了无数的示例,但是字典和treeviews的混合使用使我感到困惑。这是一个小测试程序,我在insert语句中做错了什么?在

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离开我的背部,以验证的例子。在


Tags: textfromimportmessage字典tkintercolumnordereddict
1条回答
网友
1楼 · 发布于 2024-06-16 10:52:10

替换这部分代码

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

用这个

^{pr2}$

您需要在treeview中插入作为tuple的数据,所以我将您的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()

相关问题 更多 >