Search code examples
pythontkintertreeviewttk

Clear the selection after clicking a blank space


I'm currently using python 3.9 and trying to clear the selection after clicking to a blank space
It looks something like this.

This is my code:

fileTreeView = ttk.Treeview(m, name='fileTreeView')
fileTreeView['columns']=('name', 'datem', 'type', 'size', 'blankspace')
fileTreeView.column('#0', width=0, stretch=NO)
fileTreeView.column('name',  width=60)
fileTreeView.column('datem',  width=60)
fileTreeView.column('type',  width=60)
fileTreeView.column('size',  width=60)
fileTreeView.column('blankspace', width=60)

fileTreeView.heading('#0')
fileTreeView.heading('name', text='Name')
fileTreeView.heading('datem', text='Date modified')
fileTreeView.heading('type', text='Type')
fileTreeView.heading('size', text='Size')
fileTreeView.heading('blankspace', text="")

I want when the blankspace column is clicked, it will clear the selection.

Thanks in advance!


Solution

  • You can find the column being clicked inside the callback of <Button-1> event, if it is blankspace then clear the selection:

    def on_clicked(event):
        # get the column index being clicked
        col = fileTreeView.identify_column(event.x)
        # get the column name of the clicked column
        name = fileTreeView.column(col, 'id')
        if name == 'blankspace':
            # clear the selection
            fileTreeView.selection_set()
            # disable default mouse click handler
            return 'break'
    
    fileTreeView.bind('<Button-1>', on_clicked)