问题
What would be the best way to give an error and tell the user to only input numbers if they type letters as an input? Code that doesn't work:
if self.localid_entry.get() == int(self.localid_entry.get():
self.answer_label['text'] = "Use numbers only for I.D."
The variable is obtained in Tkinter with:
self.localid2_entry = ttk.Entry(self, width=5)
self.localid2_entry.grid(column=3, row=2)
回答1:
Something like this:
try:
i = int(self.localid_entry.get())
except ValueError:
#Handle the exception
print 'Please enter an integer'
回答2:
The best solution is to use the validation feature to only allow integers so you don't have to worry about validation after the user is done.
See https://stackoverflow.com/a/4140988/7432 for an example that allows only letters. Converting that to allow only integers is trivial.
回答3:
Bryan has the correct answer, but using tkinter's validation system is pretty bulky. I prefer to use a trace on the variable to check. For instance, I can make a new type of Entry that only accepts digits:
class Prox(ttk.Entry):
'''A Entry widget that only accepts digits'''
def __init__(self, master=None, **kwargs):
self.var = tk.StringVar(master)
self.var.trace('w', self.validate)
ttk.Entry.__init__(self, master, textvariable=self.var, **kwargs)
self.get, self.set = self.var.get, self.var.set
def validate(self, *args):
value = self.get()
if not value.isdigit():
self.set(''.join(x for x in value if x.isdigit()))
You would use it just like an Entry widget:
self.localid2_entry = Prox(self, width=5)
self.localid2_entry.grid(column=3, row=2)
来源:https://stackoverflow.com/questions/42848360/how-to-tell-user-to-only-use-integers-if-they-input-string-in-python-tkinter