我正在为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方法将类型作为字符串返回,而不是作为插入的对象.如何让它返回插入的对象?

推荐答案

我不相信这是可能的.添加到TreeView小部件的数据必须先转换为字符串或数字,然后才能在该小部件中显示.这是因为底层的tcl/tk库不了解任何有关python类的信息.当您重新获得数据时,它将是一个字符串和数字的列表.

Python-3.x相关问答推荐

Pandas 数据帧断言等同于NaN

我没有';无法理解此TemplateDoesNotExist错误

新行是pandas数据帧中旧行的组合

在 Python 中比较和排序列之间的值(带有不匹配列)

在python内的powershell中转义$_

切片的Python复杂性与元组的星号相结合

有没有一种方法可以通过输入从 0 到 255 的 R、G 和 B 值来生成 RGB colored颜色 ,而无需使用 python 中的 matplotlib 模块?

是否可以将多个 if 转换为数组?

在气流中运行 DAG 时出现处理信号:ttou消息

django rest框架中的save()、create()和update()有什么区别?

Generic[T] 基类 - 如何从实例中获取 T 的类型?

python total_ordering:为什么使用 __lt__ 和 __eq__ 而不是 __le__?

如何判断一个字符串是否包含有效的 Python 代码

Python 类型提示语法如何/为什么起作用?

Python中的依赖倒置

在 Python 3 中获取所有超类

同步调用协程

Python 2 与 Python 3 - urllib 格式

TypeError:无法实例化类型元组;使用 tuple() 代替

Pylint 中的模块PyQt5.QtWidgets错误中没有名称QApplication