K
K
Konstantin Ermolaev2021-07-09 10:36:33
Python
Konstantin Ermolaev, 2021-07-09 10:36:33

How to get the name of a ttk.treeview cell as a variable when clicking on it?

I have a tkinter window that contains a treeview widget in the form of a table. The table takes data from the sqlite3 database. The data is dynamic and will be regularly changed, added, removed. The first column of the table stores an identifier for each row - it will be necessary to work on it in the future. Required: when clicking on a line, display this identifier as a variable.

Here is the table code:

class Table(tk.Frame):
    def __init__(self, parent=None, headings=tuple(), rows=tuple()):
        super().__init__(parent)
        
        table = ttk.Treeview(self, show="headings", selectmode="browse")
        table["columns"] = headings
        table["displaycolumns"] = headings
  
        for head in headings:
            table.heading(head, text=head, anchor=tk.CENTER)
            table.column(head, anchor=tk.CENTER, width=20)
  
        for row in rows:
            table.insert('', tk.END, values=tuple(row))
  
        scrolltable = tk.Scrollbar(self, command=table.yview)
        scrolltable1 = tk.Scrollbar(self, command= table.xview)
        table.configure(yscrollcommand=scrolltable.set)
        table.configure(xscrollcommand=scrolltable1.set)
        scrolltable.pack(side=tk.RIGHT, fill=tk.Y)
        scrolltable1.pack(side=tk.BOTTOM, fill=tk.X)
        table.pack(expand=tk.YES, fill=tk.BOTH)

data = (',')
with sqlite3.connect('mydatabase.db') as connection:
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM service_data WHERE [Вид обслуживания] ='РЕМОНТ'")
    data = (row for row in cursor.fetchall())
60e7fc5619000210392861.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2021-07-09
@Lomonos1917

You need to set the focus and then get the data from the selected row of the TreeView, something like this

row_id = table.focus()
print(row_id)
if row_id:
    order_num = table.item(row_id)['values'][0]
    print(order_num)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question