I need some help with cursor event handling in python+Tkinter

Question!

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.

By : Ben Lever


Answers

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();


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

By : monkut


Assuming PCRE (Perl regexes), I am not sure that you can do it at all easily. The AND operation is concatenation of regexes, but you want to be able to permute the order in which the words appear without having to formally generate the permutation. For N words, when N = 2, it is bearable; with N = 3, it is barely OK; with N > 3, it is unlikely to be acceptable. So, the simple iterative solution - N regexes, one for each word, and iterate ensuring each is satisfied - looks like the best choice to me.



This video can help you solving your question :)
By: admin