Skip to content
Advertisement

Tkinter Python – how to set a command for a column

I want to create a table like this:

I want it to work such that when I click on “delete this record” it will delete that row of data. I am trying this code:

from tkinter import *
from tkinter import ttk


def doAnything():
    print("Do any thing")


ws = Tk()
ws.title('Help')

tv = ttk.Treeview(ws)
tv['columns'] = ('Rank', 'Name', 'Badge')
tv.column('#0', width=0, stretch=NO)
tv.column('Rank', anchor=CENTER, width=80)
tv.column('Name', anchor=CENTER, width=80)
tv.column('Badge', anchor=CENTER, width=80)

tv.heading('#0', text='', anchor=CENTER)
tv.heading('Rank', text='Id', anchor=CENTER, command=lambda: doAnything())
tv.heading('Name', text='rank', anchor=CENTER)
tv.heading('Badge', text='Badge', anchor=CENTER)

tv.insert(parent='', index=0, iid=0, text='',
          values=('1', 'Vineet', 'delete this record'))
tv.insert(parent='', index=1, iid=1, text='',
          values=('2', 'Anil', 'delete this record'))
tv.insert(parent='', index=2, iid=2, text='',
          values=('3', 'Vinod', 'delete this record'))
tv.insert(parent='', index=3, iid=3, text='',
          values=('4', 'Vimal', 'delete this record'))
tv.insert(parent='', index=4, iid=4, text='',
          values=('5', 'Manjeet', 'delete this record'))
tv.pack(fill=BOTH, expand=True)


ws.mainloop()

Advertisement

Answer

You can bind <ButtonRelease-1> on the treeview and then determine whether user has clicked on the required cells. If yes, ask for confirmation and delete the row:

from tkinter.messagebox import askyesno

...

def on_click(event):
    col = tv.identify_column(event.x)
    # check whether "Badge" column is clicked
    if col == '#3':
        row = tv.identify_row(event.y)
        # a row is clicked, so ask for confirmation of the deletion
        if row and askyesno('Confirmation', f'Are you sure to delete the row: {tv.item(row)["values"][:2]}?'):
            tv.delete(row)

tv.bind('<ButtonRelease-1>', on_click)

...
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement