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:
JavaScript
x
39
39
1
from tkinter import *
2
from tkinter import ttk
3
4
5
def doAnything():
6
print("Do any thing")
7
8
9
ws = Tk()
10
ws.title('Help')
11
12
tv = ttk.Treeview(ws)
13
tv['columns'] = ('Rank', 'Name', 'Badge')
14
tv.column('#0', width=0, stretch=NO)
15
tv.column('Rank', anchor=CENTER, width=80)
16
tv.column('Name', anchor=CENTER, width=80)
17
tv.column('Badge', anchor=CENTER, width=80)
18
19
tv.heading('#0', text='', anchor=CENTER)
20
tv.heading('Rank', text='Id', anchor=CENTER, command=lambda: doAnything())
21
tv.heading('Name', text='rank', anchor=CENTER)
22
tv.heading('Badge', text='Badge', anchor=CENTER)
23
24
tv.insert(parent='', index=0, iid=0, text='',
25
values=('1', 'Vineet', 'delete this record'))
26
tv.insert(parent='', index=1, iid=1, text='',
27
values=('2', 'Anil', 'delete this record'))
28
tv.insert(parent='', index=2, iid=2, text='',
29
values=('3', 'Vinod', 'delete this record'))
30
tv.insert(parent='', index=3, iid=3, text='',
31
values=('4', 'Vimal', 'delete this record'))
32
tv.insert(parent='', index=4, iid=4, text='',
33
values=('5', 'Manjeet', 'delete this record'))
34
tv.pack(fill=BOTH, expand=True)
35
36
37
ws.mainloop()
38
39
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:
JavaScript
1
17
17
1
from tkinter.messagebox import askyesno
2
3
4
5
def on_click(event):
6
col = tv.identify_column(event.x)
7
# check whether "Badge" column is clicked
8
if col == '#3':
9
row = tv.identify_row(event.y)
10
# a row is clicked, so ask for confirmation of the deletion
11
if row and askyesno('Confirmation', f'Are you sure to delete the row: {tv.item(row)["values"][:2]}?'):
12
tv.delete(row)
13
14
tv.bind('<ButtonRelease-1>', on_click)
15
16
17