'How to add checkbuttons to every row of a table read from csv in tkinter?

I have a table with 4 columns that are read from csv and displayed using tkinter. I want to a checkbutton at the end of every row in the column called 'Served'. However instead of getting a checkbutton I get '.!framed.!checkbut'.

Here is my code:

from tkinter import *
from tkinter import ttk
from ttkthemes import ThemedStyle
import tkinter.font as font
import csv

root = Tk()
root.title("A") #title shown in bar
root.iconbitmap(r'C:/Users/...') #icon shown in bar
TableMargin = ttk.Frame(root)
TableMargin.grid(column=0, row=0, sticky=(N, W, E, S))
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
root.state('zoomed') #fullscreen

# Setting Theme
style = ThemedStyle(TableMargin)
style.set_theme("black")

#Heading
label = ttk.Label(TableMargin, text='Orders')
label['font'] = font.Font(size=20, weight="bold")
label.grid(row=0, sticky=(N),pady=5)

#Designing of Table
style = ttk.Style()
style.configure("Treeview.Heading", font=(None, 13))
# scrollbarx = Scrollbar(TableMargin, orient=HORIZONTAL)
# scrollbary = Scrollbar(TableMargin, orient=VERTICAL)
tree = ttk.Treeview(TableMargin, columns=("Table No.", "Order", "Time", "Served"), height=400, selectmode="extended") #, yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set
# scrollbary.config(command=tree.yview)
# scrollbary.pack(side=RIGHT, fill=Y)
# scrollbarx.config(command=tree.xview)
# scrollbarx.pack(side=BOTTOM, fill=X)
tree.heading('Table No.', text="Table No.", anchor=W)
tree.heading('Order', text="Order", anchor=W)
tree.heading('Time', text="Time", anchor=W)
tree.heading('Served', text="Served", anchor=W)
tree.column('#0', stretch=NO, minwidth=0, width=0)
tree.column('#1', stretch=NO, minwidth=0, width=100)
tree.column('#2', stretch=NO, minwidth=0, width=600)
tree.column('#3', stretch=NO, minwidth=0, width=100)
tree.column('#4', stretch=NO, minwidth=0, width=100)

tree.grid(row=0, pady=50,padx=190,sticky=(N, E, S))

with open('C:/Users/...', encoding = "utf-8-sig") as f:
    reader = csv.DictReader(f, delimiter=',')
    for row in reader:
        table = row['Table']
        order = row['Order']
        time = row['Time']
        var = IntVar()
        served = ttk.Checkbutton(TableMargin, text="", variable=var)
        served.grid()
        tree.insert("", 1, values=(table, order, time, served))


Solution 1:[1]

You can do it using images for the checkboxes. First, I use the Row layout to put the image on the right:

style.layout('cb.Treeview.Row',
                     [('Treeitem.row', {'sticky': 'nswe'}),
                      ('Treeitem.image', {'side': 'right', 'sticky': 'e'})])

Then, I use the tags 'checked' and 'unchecked' on each tree item to control the image for the checkbox (see code below).

I also add the item's id as a tag to each item so that I can bind this tag to button clicks. When there is a click, I check with identify_column(event.x) that the click is in the 'Served' column and if so I toggle the checkbox's state using the tags.

Here is the full code:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()


class CbTreeview(ttk.Treeview):
    def __init__(self, master=None, **kw):
        kw.setdefault('style', 'cb.Treeview')
        kw.setdefault('show', 'headings')  # hide column #0
        ttk.Treeview.__init__(self, master, **kw)
        # create checheckbox images
        self._im_checked = tk.PhotoImage('checked',
                                         data=b'GIF89a\x0e\x00\x0e\x00\xf0\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x0e\x00\x0e\x00\x00\x02#\x04\x82\xa9v\xc8\xef\xdc\x83k\x9ap\xe5\xc4\x99S\x96l^\x83qZ\xd7\x8d$\xa8\xae\x99\x15Zl#\xd3\xa9"\x15\x00;',
                                         master=self)
        self._im_unchecked = tk.PhotoImage('unchecked',
                                           data=b'GIF89a\x0e\x00\x0e\x00\xf0\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x0e\x00\x0e\x00\x00\x02\x1e\x04\x82\xa9v\xc1\xdf"|i\xc2j\x19\xce\x06q\xed|\xd2\xe7\x89%yZ^J\x85\x8d\xb2\x00\x05\x00;',
                                           master=self)
        style = ttk.Style(self)
        style.configure("cb.Treeview.Heading", font=(None, 13))
        # put image on the right
        style.layout('cb.Treeview.Row',
                     [('Treeitem.row', {'sticky': 'nswe'}),
                      ('Treeitem.image', {'side': 'right', 'sticky': 'e'})])

        # use tags to set the checkbox state
        self.tag_configure('checked', image='checked')
        self.tag_configure('unchecked', image='unchecked')

    def tag_add(self, item, tags):
        new_tags = tuple(self.item(item, 'tags')) + tuple(tags)
        self.item(item, tags=new_tags)

    def tag_remove(self, item, tag):
        tags = list(self.item(item, 'tags'))
        tags.remove(tag)
        self.item(item, tags=tags)

    def insert(self, parent, index, iid=None, **kw):
        item = ttk.Treeview.insert(self, parent, index, iid, **kw)
        self.tag_add(item, (item, 'unchecked'))
        self.tag_bind(item, '<ButtonRelease-1>',
                      lambda event: self._on_click(event, item))

    def _on_click(self, event, item):
        """Handle click on items."""
        if self.identify_row(event.y) == item:
            if self.identify_column(event.x) == '#4': # click in 'Served' column
                # toggle checkbox image
                if self.tag_has('checked', item):
                    self.tag_remove(item, 'checked')
                    self.tag_add(item, ('unchecked',))
                else:
                    self.tag_remove(item, 'unchecked')
                    self.tag_add(item, ('checked',))



tree = CbTreeview(root, columns=("Table No.", "Order", "Time", "Served"),
                  height=400, selectmode="extended")

tree.heading('Table No.', text="Table No.", anchor='w')
tree.heading('Order', text="Order", anchor='w')
tree.heading('Time', text="Time", anchor='w')
tree.heading('Served', text="Served", anchor='w')
tree.column('#1', stretch='no', minwidth=0, width=100)
tree.column('#2', stretch='no', minwidth=0, width=600)
tree.column('#3', stretch='no', minwidth=0, width=100)
tree.column('#4', stretch='no', minwidth=0, width=70)

tree.pack(fill='both')

for i in range(5):
    tree.insert('', 'end', values=(i, i, i))
root.mainloop()

screenshot

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 j_4321