Edward Garemo
Edward Garemo

Reputation: 474

Tkinter: Can you see all bindings of a widget?

In my application I want to toggle between two states, and in each of the states I want -> don't want various keys bound.

Right now what I've done is that in my class I've created an attribute self.bindings = [] and then I have a method to create bindings:

def _create_bindings(self):
    self.bind("<Button-1>", self._canvas_on_click)
    self.bindings.append("<Button-1>")
    self.bind("<Double-Button-1>", self._canvas_on_2click)
    self.bindings.append("<Double-Button-1>")
    self.bind("<<arrow>>", self._canvas_on_arrows)
    self.bindings.append("<<arrow>>")
    self.bind("<space>", lambda event: self._toggle_selected())
    self.bindings.append("<space>")
    self.bind("<Key>", self._canvas_on_key_press)
    self.bindings.append("<Key>")
    self.bind("<BackSpace>", lambda event: self._empty_cell())
    self.bindings.append("<BackSpace>")
    self.bind("<Escape>", self._esc)
    self.bindings.append("<Escape>")

and then to remove them:

def _remove_bindings(self):
    for b in self.bindings:
        self.unbind(b)

It's not terrible but it does lead to some duplication (see create function: create binding + add to list).

I could create a wrapper to combine these two steps, but regardless I still have an extra attribute to manage.

Is there a function which I can call which would provide me the same information as self.bindings above?

Upvotes: 5

Views: 1115

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 385970

If you call the bind method without any parameters it will return a list of all events that you have bound for that widget. Your _remove_bindings could look like this:

def _remove_bindings(self):
    for event in self.bind():
       self.unbind(event)

Upvotes: 5

Edward Garemo
Edward Garemo

Reputation: 474

There is no need to remove the bindings.

Altering the 'state' attribute of the e.g. Canvas, Button disables any bindings.

Upvotes: 0

Related Questions