Tkinter unbinding

Peter Otten __peter__ at web.de
Fri Dec 19 15:33:07 CET 2008


Roger wrote:

>> Note that I took out the lambdas and gave event arguments to the
>> functions; if you did that on purpose, because you need to call the same
>> functions without events, then just ignore that...
>> SO, the other workaround, which I've used, is to bind the event to a
>> generic function, and have that generic function conditionally call
>> the functions you want. I'll go back and try to make an example from
>> your example. -Chuckk
> 
> Thanks Chuckk!  You've done exactly what I did so far.  I went through
> the source in Tkinter.py and had an inkling of what the unbind
> function was doing.  I believe, and please correct me if I'm wrong,
> in: self.tk.call('bind', self._w, sequence, '') , the '' is unbinding
> all methods and I believe the self.deletecommand(funcid) is a
> workaround for a memory leak otherwise.  Perhaps self.tk.call('bind',
> self._w, sequence, funcid) would work but that's a pure guess.  I
> would have liked to investigate the tcl source directly to see if I
> could develop a workaround through a tk.call() but that was hitting a
> wall in terms of any documentation I could research.  I'm interested
> in any workaround you may have however!

The documentation for bind in tcl is here

http://www.tcl.tk/man/tcl8.4/TkCmd/bind.htm

and as far as I understand it doesnt support unbinding selected callbacks,
either. I'd suggest a plain-python workaround along the lines of

import Tkinter

def test(event):
    print 'test'

def test2(event):
    print 'test2'

root = Tkinter.Tk()
root.geometry("200x100+100+100")

class Multiplexer:
    def __init__(self):
        self.funcs = []
    def __call__(self, event):
        for f in self.funcs:
            f(event)
    def add(self, f):
        self.funcs.append(f)
        return f
    def remove(self, f):
        self.funcs.remove(f)

m = Multiplexer()
m.add(test)
m.add(test2)
root.bind("<1>", m)

def unbind():
    print "unbind"
    m.remove(test2)

button = Tkinter.Button(root, text="unbind test2", command=unbind)
button.pack()

root.mainloop()

Peter



More information about the Python-list mailing list