Home > Software design >  How to restrict the maximum number a user can enter in an entry widget?
How to restrict the maximum number a user can enter in an entry widget?

Time:09-23

I have an entry widget where I would like the user to only be able to enter a number between 0 and 100. I figured out how to only let the user enter numbers but now I don't know how to keep track of what is entered in the widget and make sure it is not more than 100....

from tkinter import *


class Prox(Entry):
    '''Entry widget that only accepts digits'''
    def __init__(self, master=None, **kwargs):
        self.var = StringVar(master)
        self.var.trace('w', self.validate)
        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()))

def character_limit(entry_text):
    if len(entry_text.get()) > 0:
        entry_text.set(entry_text.get()[-1])

window = Tk()

percEntry = Prox(window)
percEntry.insert(0, '0')
percEntry.grid(row=0, column=0)

window.mainloop()

CodePudding user response:

In this case , try using SpinBox Instead of Entry Widget .

For example :

from tkinter import *  
  
top = Tk()  
  
top.geometry("200x200")  

spin = Spinbox(top, from_= 0, to = 25)  
  
spin.pack()  

top.mainloop()  

To get the SpinBox current value , you can just simply do : spin.get()

  • Related