Skip to main content
 首页 » 编程设计

python之从 TreeView 中选择数据

2024年10月24日8softidea

我将 ttk.TreeView 用作多列 ListBox,它可以有效地显示我作为表格发送给它的 sql 数据。当我进行 sql 查询并且 TreeView 显示查询的数据时,有一个选择数据的选项,因为单击时该行会突出显示。我是否可以单击一行以突出显示数据,然后单击另一个按钮创建一个弹出窗口,其中包含要编辑的数据?

因为我正在使用 SQL,所以我只需要选择数据,然后我就可以使用它从 SQL 表中删除它,而不是从 TreeView 表中删除。这是下面的树,其中包含一些数据被选中的示例。我可以只传递选定的要编辑或删除的数据或类似的东西吗?

The tree

编辑:

        def OnDoubleClick(self,event): 
            top1=Toplevel(height=600,width=500) 
            #frame is just for managing objects not absolutely needed but i think it is good 
            #to use frame when using object so i have kept it in 
            curItem = self.tree.focus() 
            contents =(self.tree.item(curItem)) 
            selectedetails = contents['values']  
            #this is what you would use to when presenting the selectedd information 
 
 
            self.example_var = StringVar() 
            self.example_var.set(selectedetails[1]) 
            self.example_txt = Entry(top1,textvariable=self.example_var) 
            self.example.grid(row=1,column=1) 

我将用于管理对象的框架更改为 Toplevel 并更改了条目小部件的位置,使其位于同一位置 (top1)。当我双击树中的项目时产生的错误消息是:

Exception in Tkinter callback 
Traceback (most recent call last): 
    File "C:\Python33\lib\tkinter\__init__.py", line 1489, in __call__ 
        return self.func(*args) 
    File "C:\Users\lukeh\Documents\a\test for double click.py", line 278, in OnDoubleClick 
        self.example.grid(row=1,column=1) 
AttributeError: 'MultiColumnListbox' object has no attribute 'example' 

当我删除 self.example 开始的代码的后半部分时,代码实际上似乎除了创建 Toplevel 之外没有做任何事情。

编辑:

当我删除 self.example 代码行并仅使用 print (selectedetails) 时,会输出正确的数据行。

请您参考如下方法:

首先你需要绑定(bind)一个事件到你的树 iv 使用双击

self.tree.bind("<Double-1>",lambda event :self.OnDoubleClick(event)) 
#note the OnDoubleClick is the name of the sub that python will look for when tree  
#double clicked 

接下来你需要制作你的子程序,当树双击时将被调用(在我的例子中它是 OnDoubleClick)

def OnDoubleClick(self, event): 
        frame3 = tk.LabelFrame(self, text="frame1", width=300, height=130, bd=5) 
        frame3.grid(row=2, column=0, columnspan=3, padx=8) 
        #frame is just for managing objects not absolutely needed but i think it is good 
        #to use frame when using object so i have kept it in 
        curItem = self.tree.focus() 
        contents =(self.tree.item(curItem)) 
        selectedetails = contents['values']  
        #this is what you would use to when presenting the selectedd information 

然后要访问此选定数据,只需使用带有所需缩进的数组名称(在本例中为 selectedetails)。然后,我使用字符串变量用所选数据填充条目。

self.example_var = StringVar() 
self.example_var.set(selectedetails[1]) 
self.example_txt = Entry(frame3,textvariable=self.example_var) 
self.example_txt.grid(row=1,column=1)