views:

752

answers:

3

Hey,

I'm building a code in which I'd like to be able to generate an event when the user changes the focus of the cursor from an Entry widget to anywhere, for example another entry widget, a button...

So far i only came out with the idea to bind to TAB and mouse click, although if i bind the mouse click to the Entry widget i only get mouse events when inside the Entry widget.

How can i accomplish to generate events for when a widget loses cursor focus?

Any help will be much appreciated!

Thanks in advance!

William.

A: 

This isn't specific to tkinter, and it's not focus based, but I got an answer to a similar question here:

http://stackoverflow.com/questions/165495/detecting-mouse-clicks-in-windows-using-python

I haven't done any tkinter in quite a while, but there seems to be "FocusIn" and "FocusOut" events. You might be able to bind and track these to solve your issue.

From: http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm

monkut
A: 

Thanks,

that Focus in and out is mouse basted tho... i needed something cursor based...

the topic helps a little, not the way i expected but its helpful.

i needed i think ill just try to capture mouse clicks on the outermost widget of my application and capture tab commands inside the inner widget... my goal is to update the whole application interface based on the parameters the user specified in the entry widgets any time that any entry widget loses cursor focus...

well, thanks anyway! a lot!

William.

You are incorrect about FocusIn/FocusOut. They are exactly what you want. See an example in my answer.
Bryan Oakley
+1  A: 

The events <FocusIn> and <FocusOut> are what you want. Run the following example and you'll see you get focus in and out bindings whether you click or press tab (or shift-tab) when focus is in one of the entry widgets.

from Tkinter import *

def main():
    global text

    root=Tk()

    l1=Label(root,text="Field 1:")
    l2=Label(root,text="Field 2:")
    t1=Text(root,height=4,width=40)
    e1=Entry(root)
    e2=Entry(root)
    l1.grid(row=0,column=0,sticky="e")
    e1.grid(row=0,column=1,sticky="ew")
    l2.grid(row=1,column=0,sticky="e")
    e2.grid(row=1,column=1,sticky="ew")
    t1.grid(row=2,column=0,columnspan=2,sticky="nw")

    root.grid_columnconfigure(1,weight=1)
    root.grid_rowconfigure(2,weight=1)

    root.bind_class("Entry","<FocusOut>",focusOutHandler)
    root.bind_class("Entry","<FocusIn>",focusInHandler)

    text = t1
    root.mainloop()

def focusInHandler(event):
    text.insert("end","FocusIn %s\n" % event.widget)
    text.see("end")

def focusOutHandler(event):
    text.insert("end","FocusOut %s\n" % event.widget)
    text.see("end")


if __name__ == "__main__":
    main();
Bryan Oakley