我正在为TreeView的每一行插入一个id和名称以及实际的类项目. 当我 Select 一行并希望取回该对象时,我得到的是一个字符串对象,而不是类对象.如何取回类对象而不是字符串?
import tkinter as tk
from tkinter import ttk
class TreeViewApp(tk.Tk):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.geometry("600x400+400+50")
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
frame = ttk.Frame(self)
frame.columnconfigure(0, weight=1)
frame.rowconfigure(0, weight=1)
frame.grid(column=0, row=0, sticky="nesw")
tablesDG = ttk.Treeview(frame, height=5)
tablesDG.bind("<<TreeviewSelect>>", self.onListSelect)
tablesDG['columns'] = ('id', 'name', 'data')
tablesDG.heading('#0', text="")
tablesDG.heading('id', text="")
tablesDG.heading('name', anchor='w', text=" Name")
tablesDG.heading('data', text="")
tablesDG.column('#0', width= 0, stretch=False)
tablesDG.column('id', width=0, stretch=False)
tablesDG.column('name', anchor='w', width=100)
tablesDG.column('data', width= 0, stretch=False)
tablesDG.grid(column=0, row=0, sticky="nesw")
# creating row objects.
# Note that the data column I am saving the actual object for retrieval later
for x in range(5):
obj = dataDTO()
obj.id = x
obj.name = f'obj{x}'
tablesDG.insert('', 'end', values=(obj.id, obj.name, obj))
# output of print. Notice that the class of data is string and not dataDTO class object.
# {'text': '', 'image': '', 'values': [0, 'obj0', '<__main__.dataDTO object at 0x000002BA40075C90>'], 'open': 0, 'tags': ''}
# <class 'str'>
def onListSelect(self, event):
selected_iid = event.widget.selection()[0]
row = event.widget.item(selected_iid)
print(row)
print(type(row['values'][2]))
class dataDTO():
pass
TreeViewApp()
tk.mainloop()
如您所见,onListSelect
方法将类型作为字符串返回,而不是作为插入的对象.如何让它返回插入的对象?