[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

tkinter treeview widget - bind doubleclick to items only ?

On 2020-01-20 10:49, R.Wieser wrote:
> Hello all,
> I've create a treeview, and would (ofcourse) want to register some
> mouse-clicking on it, and for that I've found the ".bind()" method.
> There is a slight problem with it though: when I click a columns caption
> (for sorting) the events code also gets fired, which causes problems.
> I've found that I can connect mouse-click events to the column captions  as
> shown in the second example here in the "self.tree.heading()" call :
> I was wondering if something similar is maybe also available for the items
> below it ...
> If not, how do I ignore mouseclicks that are not done on one of the items ?
You set the event handler for the column headings separately from that 
for the items.

Here's an example:

# -*- coding: utf-8 -*-
import tkinter as tk
import tkinter.ttk as ttk

class App(tk.Tk):
     def __init__(self):
         self.title('Treeview Example')

         self.treeview = ttk.Treeview(self, columns=['#1'],
           displaycolumns='#all', show=['headings'])
         self.treeview.heading('#1', text='Items', command=lambda iid='#1':
         self.treeview.bind('<Double-1>', self.on_dclick)
         self.treeview.pack(fill='both', expand=True)

         for i in range(5):
             iid = self.treeview.insert('', 'end')
             self.treeview.set(iid, '#1', 'Item %d' % (1 + i))

     def on_heading(self, iid):
         print('Clicked on column %s' % iid, flush=True)
         selection = self.treeview.selection()
         print('Selection is %s' % ascii(selection), flush=True)

     def on_dclick(self, event):
         print('Double-clicked on an item', flush=True)
         selection = self.treeview.selection()
         print('Selection is %s' % ascii(selection), flush=True)



If you click on the column heading you get:

Clicked on column #1
Selection is ...

If you double-click on, say, item 1, you get:

Double-clicked on an item
Selection is ('I001',)