How To I Create An Event For User Entry?
Solution 1:
The way to do what you literally asked, "the 'Enter' button to become active once the user has actually started typing" is to bind the change or keypress event on the enter_name
, and activate Enter_0
once it's triggered.
But that's probably not what you actually want. If the user enters some text and then deletes it, wouldn't it be nicer if the button disabled again? And if the user pastes some text without typing anything, shouldn't that enable the button?
To do that, you want one of two things: validation, or variable tracing.
Before we get into it, you're almost certainly going to want to store the Enter_0
button as an attribute on self
instead of creating and re-creating new buttons on top of each other. So, I'll do that in my example.
Validation, although it's very badly documented in Tkinter and a bit clumsy to use, is very powerful, and the obvious fit for what you're trying to do—validate text:
def__init__(self, parent):
# existing stuff
vcmd = self.root.register(self.validate)
enter_name = Entry(self, validate='key', validatecommand=(vcmd, '%P'))
# existing stuff
self.Enter_0 = Button(self, text="Enter", width=10, command=callback)
self.Enter_0.pack()
defvalidate(self, P):
self.Enter_0.config(state=(NORMAL if P else DISABLED))
returnTrue
This probably looks like unreadable magic, and the Tkinter docs give you no guidance. But the Tk docs for validatecommand
show what it means:
- The
key
bit means that the command "will be called when the entry is edited". - The
%P
means the "value of the entry if the edit is allowed". You can stick as many of those%
strings as you want into yourvcmd
, and they will be passed as arguments to yourvalidate
method. So, you could pass(vcmd, '%s', '%P', '%v')
and then definevalidate(self, s, P, v)
. - You can do anything you want in the function, and then return
True
orFalse
to accept or reject the change (or returnNone
to stop calling your validation function).
Anyway, now, if the user attempts to edit the entry in any way, then the Enter_0
button will be set to NORMAL
if their edit would give you a non-empty string, DISABLED
otherwise.
Variable tracing is conceptually a lot clunkier, but in practice often simpler. It's also not completely documented, but at least it's somewhat documented.
The idea is to create a StringVar
, attach it to the Entry
, and put a "write trace" on it, which is a function that gets called every time the variable is updated (which happens every time the Entry
changes contents). Like this:
def__init__(self, parent):
# existing stuff
name_var = StringVar()
defvalidate_enter():
self.Enter_0.config(state=(NORMAL if var.get() else DISABLED))
name_var.trace('w', lambda name, index, mode: validate_enter)
enter_name = Entry(self, textvariable=name_var)
# existing stuff--and again, do the self.Enter_0 change
Post a Comment for "How To I Create An Event For User Entry?"