Tkinter Python - 如何为列设置命令

Tkinter Python - how to set a command for a column

我想创建一个这样的table:

我希望它能在我点击“删除此记录”时删除该行数据。我正在尝试这段代码:

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

您可以在树视图上绑定<ButtonRelease-1>,然后判断用户是否点击了所需的单元格。如果是,请确认并删除该行:

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)

...