我正在开发一个解码can bus错误消息的程序。这些消息被准确地读入字典,但是我在将它们显示在树视图中时遇到了麻烦。我已经阅读了插入方法并查找了无数的例子,但字典和树视图的混合使我感到困惑。这是一个小测试程序,我在插入语句中做错了什么?
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。
答案 0 :(得分:2)
替换这部分代码
Errortree.insert("", 'end', TestDict['MsgID'], TestDict['OtherData'])
用这个
Errortree.insert("", 'end', values=(TestDict['MsgID'], TestDict['OtherData']))
您需要将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()