focus trap in tkinter

vigacmoe at gmail.com vigacmoe at gmail.com
Mon Apr 9 15:27:26 CEST 2007


Hi all,

I'm trying to write a simple tkinter program, then this problem popped
up. The followin code will describe the problem.

------------------------------------------

import Tkinter

class countdown(Tkinter.Frame):
        def __init__(self, master = None):
                Tkinter.Frame.__init__(self, master)
                self.ticker = Tkinter.Label(self)
                self.pack()
                self.ticker.pack()
                self.ticker["text"] = "foo"
                self.master.bind("<FocusIn>", self.__focus_in)
                self.master.bind("<FocusOut>", self.__focus_out)
                self.master.wm_attributes("-topmost", 1)

        def __focus_in(self, detail):
                self.master.wm_attributes("-alpha", 1)

        def __focus_out(self, detail):
                self.master.wm_attributes("-alpha", 0.8)


if ("__main__" == __name__):
        root = Tkinter.Tk()
        app = countdown(master = root)
        app.mainloop()

------------------------------------------

My aim is to set the alpha property of the toplevel window to 0.8 when
it lose focus, and set it back to 1 when it regain focus, pretty
simple. But the problem is, whenever wm_attributes() is called, a new
focus event is generated, and then wm_attributes() will be called
again, then the program runs into endless loop of receiving focus
events. Simply run above code will see what's going on.

I tried to disable FocusIn event in the event handlers, by calling
self.master.unbind(), but it doesn't work.

I also tried to bind FocusIn and FocusOut event to the frame, the
label widgets, instead of the toplevel window, but both frame and
label widgets doesn't receive focus event, even after I set their
takefocus properties to 1.

There should be a way to make it work, just I didn't find it. Any
input?

Best regards!




More information about the Python-list mailing list