1

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 generate events for when a widget loses cursor focus?

Thanks in advance!

2 Answers 2

5

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.