1

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
  • Use try/except to catch the error when int() fails. Commented Mar 17, 2017 at 2:52

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

Brilliant and compact solution with OO approach!
1

Something like this:

try:
    i = int(self.localid_entry.get())

except ValueError:
    #Handle the exception
    print 'Please enter an integer'

Comments

0

""" Below code restricts the ttk.Entry widget to receive type 'str'. """

    import tkinter as tk
    from tkinter import ttk


    def is_type_int(*args):
      item = var.get()
      try:
        item_type = type(int(item))
        if item_type == type(int(1)):
          print(item)
          print(item_type)
      except:
        ent.delete(0, tk.END)


    root = tk.Tk()
    root.geometry("300x300")

    var = tk.StringVar()

    ent = ttk.Entry(root, textvariable=var)
    ent.pack(pady=20)

    var.trace("w", is_type_int)

    root.mainloop()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.