Reputation: 41
I want to use an entry widget to get a number between 1 and 9. If any other key is pressed I want to remove it from the display.
def onKeyPress(event):
if event.char in ['1', '2', '3', '4', '5', '6', '7', '8', '9']
...do something
return
# HERE I TRY AND REMOVE AN INVALID CHARACTER FROM THE SCREEN
# at this point the character is:
# 1) visible on the screen
# 2) held in the event
# 3) NOT YET in the entry widgets string
# as the following code shows...
print ">>>>", event.char, ">>>>", self._entry.get()
# it appeARS that the entry widget string buffer is always 1 character behind the event handler
# so the following code WILL NOT remove it from the screen...
self._entry.delete(0, END)
self._entry.insert(0, " ")
# here i bind the event handler
self._entry.bind('<Key>', onKeyPress)
OK so how can I clear the screen?
Upvotes: 2
Views: 1027
Reputation: 151
a simple way to clear the entry widget is:
from tkinter import *
tk = Tk()
# create entry widget
evalue = StringVar()
e = Entry(tk,width=20,textvariable=evalue)
e.pack()
def clear(evt):
evalue.set("") # the line that removes text from Entry widget
tk.bind_all('<KeyPress-Return>',clear) #clears when Enter is pressed
tk.mainloop()
you can use this in whatever context you wish, this is just an example
Upvotes: 0
Reputation: 10721
import Tkinter as tk
class MyApp():
def __init__(self):
self.root = tk.Tk()
vcmd = (self.root.register(self.OnValidate),
'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
self.entry = tk.Entry(self.root, validate="key",
validatecommand=vcmd)
self.entry.pack()
self.root.mainloop()
def OnValidate(self, d, i, P, s, S, v, V, W):
# only allow integers 1-9
if P == "":
return True
try:
newvalue = int(P)
except ValueError:
return False
else:
if newvalue > 0 and newvalue < 10:
return True
else:
return False
app=MyApp()
Taken from this answer with modified validation to only allow integers 1-9.
(I'm sure there is a better way to write that validation but it does the job as far as I can see.)
Upvotes: 0
Reputation: 385900
The way you are going about input validation is wrong. What you ask can't be done with the code you've posted. For one, as you've discovered, when you bind on <<Key>>
, by default that binding fires before the character is present in the widget.
I could give you workarounds, but the right answer is to use the built-in facilities for input validation. See the validatecommand
and validate
attributes of the entry widget. This answer to the question Interactively validating Entry widget content in tkinter will show you how. That answer shows how to validate against upper/lower, but it's easy to change that to compare against a set of valid characters.
Upvotes: 1