[Tkinter-discuss] Kind of the old intercept the Entry() tab key question

Michael Lange klappnase at web.de
Thu Feb 25 11:52:20 CET 2010


Hi Bob,

On Wed, 24 Feb 2010 17:15:34 -0700
Bob Greschke <bob at passcal.nmt.edu> wrote:

> I know this must have been handled before (but I can find no evidence
> of it), but what I want to do is have an entry field for filespecs
> (path+filename) that is on the same 'form' with other entry fields
> and I want the user to be able to use the Tab key to get to the field
> (so takefocus needs to be 1).
> 
> When the field has the focus if what is in the field (i.e. the
> StringVar) does not match any filename (or path) when the Tab key is
> pressed I just want the program to beep and the cursor to stay in the
> field.
> 
> If what is in there can be completed to match a filename (or path)
> then the contents gets completed when the Tab is pressed and the
> cursor stays in the field.
> 
> If what is in the field already matches a filename (or path) then the
> Tab key press goes on to the next field as it usually would for other
> Entry fields.
> 
> Is this possible?  At this point I'm still not having much luck just
> getting the cursor to stay put after a Tab press, and using return
> "break" in the <Tab> handler doesn't seem to be doing anything (I've
> only ever gotten the "break" thing to work once a long time ago, but
> then didn't use it, and I can't remember how I got it to work).
> 

Maybe you should rather use the Focus-Out event:

import Tkinter
root = Tkinter.Tk()
e = Tkinter.Entry(root)
e.pack(padx=100, pady=50)

def focus_out(event):
    if e.get() != 'foo':
        e.bell()
        e.focus_set()
e.bind('<FocusOut>', focus_out)

b = Tkinter.Button(root, text='quit', command=root.destroy)
b.pack(padx=100, pady=50)
b.focus_set()
root.mainloop()

Alternatively you can try the Entry's validatecommand, however this is
a little tricky, because you need percent substitutions:

import Tkinter
root = Tkinter.Tk()
e = Tkinter.Entry(root)
e.pack(padx=100, pady=50)

def validate(s):
    if s != 'foo':
        return 0
    return 1

def invcmd():
    e.bell()
    e.focus_set()

vcmd = (e.register(validate), '%P')
e.configure(vcmd=vcmd, validate='focusout', invcmd=invcmd)

b = Tkinter.Button(root, text='quit', command=root.destroy)
b.pack(padx=100, pady=50)
b.focus_set()
root.mainloop()


I hope this helps!

Michael




More information about the Tkinter-discuss mailing list