HarrisonDCFC
HarrisonDCFC

Reputation: 33

Treeview Select/Button Feature

For my project I am creating a table/treeview in tkinter which I am filling with data from sqlite. I want to be able to click on the data in the table which will then print the selected data in the python shell. I have looked on here to find out how to do this and I found the 'bind' feature, I have used this but when I click on the data it comes up with an error saying 'NameError: name 'tree' is not defined'. Can anyone help me with this?

This is part of my code that is used for it:

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'))

I have the required imports, window set ups etc. as well

Upvotes: 0

Views: 3378

Answers (1)

omri_saadon
omri_saadon

Reputation: 10621

You defined the tree variable in your fnstockButtonPress function.

You tried to use it in other function called fnStockClick which you didn't defined the tree variable in this function.

tree variable is local variable for the first function.

I would use an object and define the tree variable as a data member for the class so i can use it in every method.

Something like:

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'))

Upvotes: 4

Related Questions