Using tags in Treeview items

Tags are available for ttk.Treeview items, so it is possible to bind event sequences for specific rows of our contacts table.

Let's suppose that we want to open a new window to write an email to a contact when we double-click on it; however, this should only work for records where the email field is filled in.

We can easily implement this by conditionally adding a tag to the items while inserting them, and then calling tag_bind() on the widget instance with the "<Double-Button-1>" sequence—here we simply refer to the implementation of the send_email_to_contact() handler function by its name:

    columns = ("Last name", "First name", "Email")
tree = ttk.Treeview(self, show="headings", columns=columns)

for contact in csv.reader(f):
email = contact[2]
tags = ("dbl-click",) if email else ()
self.tree.insert("", tk.END, values=contact, tags=tags)

tree.tag_bind("dbl-click", "<Double-Button-1>", send_email_to_contact)

Similar to what happens when binding events to Canvas items, always remember to add the tagged items to ttk.Treeview before calling tag_bind(), because the bindings are only added to existing matching items.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset