【问题标题】:Treeview Select/Button Feature树视图选择/按钮功能
【发布时间】:2017-01-27 14:23:55
【问题描述】:

对于我的项目,我正在 tkinter 中创建一个表/树视图,我正在填充来自 sqlite 的数据。我希望能够单击表中的数据,然后在 python shell 中打印选定的数据。我在这里查看了如何执行此操作,并找到了“绑定”功能,我已经使用了这个功能,但是当我单击数据时出现错误,提示“名称错误:名称‘树’未定义’ .谁能帮我解决这个问题?

这是我用于它的代码的一部分:

def fnstockButtonPress():
    ItemID = []
    ItemName = []
    ItemDescription = []
    ItemPrice = []
    table_header = [' Item ID', ' Item Name', ' Item Description', ' Item Price (£)']
    container = Frame()
    container.place(x=25,y=200)
    tree = ttk.Treeview(columns=table_header,show="headings")
    vsb = Scrollbar(orient="vertical", command=tree.yview)
    tree.configure(yscrollcommand=vsb.set)
    tree.grid(column=0, row=0, in_=container)
    vsb.grid(column=1, row=0, sticky='ns', in_=container)
    container.grid_columnconfigure(0, weight=1)
    container.grid_rowconfigure(0, weight=1) 
    tree.column(table_header[0],width=100)
    tree.column(table_header[1],width=200)
    tree.column(table_header[2],width=100)
    tree.column(table_header[3],width=100)
    for col in table_header:
        tree.heading(col, text=col.title(), anchor = "w")
    closeButton = Button(myGui, text='Home', height=3, width=20, command=lambda :fncloseButton(container,closeButton))
    closeButton.place(x=10,y=10)
    c.execute('SELECT * FROM ItemType ORDER BY ItemID')
    result = c.fetchall()
    for x in result:
        tree.insert('', 'end', values=x)
    tree.bind('<<TreeviewSelect>>', fnStockClick)

def fnStockClick(event):
    item = tree.selection()[0]
    print('You clicked on', tree.item(item,'text'))

我也有所需的导入、窗口设置等

【问题讨论】:

    标签: python sql tkinter tree treeview


    【解决方案1】:

    您在 fnstockButtonPress 函数中定义了树变量。

    您尝试在名为 fnStockClick 的其他函数中使用它,但您没有在此函数中定义树变量。

    树变量是第一个函数的局部变量。

    我会使用一个对象并将树变量定义为类的数据成员,这样我就可以在每个方法中使用它。

    类似:

    class Test():
        def __init__(self):
            self.tree = None
        def fnstockButtonPress(self):
            ...
            self.tree = ttk.Treeview(columns=table_header,show="headings")
            self.tree.bind('<<TreeviewSelect>>', self.fnStockClick)
            ...
    
        def fnStockClick(self,event):
            item = self.tree.selection()[0]
            print('You clicked on', self.tree.item(item,'text'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-25
      • 1970-01-01
      • 2018-10-10
      • 2018-10-04
      • 1970-01-01
      相关资源
      最近更新 更多