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)
Prox
  • 699
  • 5
  • 11
  • 33

4 Answers4

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.

Community
  • 1
  • 1
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
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)
Novel
  • 13,406
  • 2
  • 25
  • 41
1

Something like this:

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

except ValueError:
    #Handle the exception
    print 'Please enter an integer'
Shubham
  • 3,071
  • 3
  • 29
  • 46
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()
osaid
  • 1
  • 1