0

I want that you can only enter numbers in the spinbox as in this question they do it in html and js, what I have done is the following code

    self.infectedDefauld = tk.StringVar(self)
    self.infectedDefauld.set("1")

    self.populationSpin = tk.Spinbox(self.leftFrame, from_=1, to=100, width=5, bg=colorFive, fg=colorFour, textvariable=self.totalDefauld, bd=10, relief="flat")
    self.populationSpin.pack(side="top", pady=5)
    self.totalDefauld.trace(mode="w", callback=self.onValidationPopulation)



   def onValidationPopulation (self, varname, elementname, mode):
       m = re.search(r'\d+', self.populationSpin.get())
       if m: 
           self.totalDefauld.set(m.group(0))
       else:
           self.totalDefauld.set(0)

the problem is that when I write for example 2 it changes to 20

larous25
  • 149
  • 7

1 Answers1

2

The spinbox -- like the Entry widget -- supports input validation. This is better than using a variable trace since a trace shouldn't be modifying the variable that is being traced. Plus, it can be used to prevent a character from being entered rather than having to remove a character after it has been entered.

Here's what it might look like in your code:

class Example(tk.Frame):
    def __init__(self, parent):
        super().__init__(parent)
        self.leftFrame = tk.Frame(self)
        self.leftFrame.pack(side="left", fill="y")

        self.populationSpin = tk.Spinbox(
            self.leftFrame, from_=1, to=100,
            width=5, bg=colorFive, fg=colorFour,
            bd=10, relief="flat",
            validate="key",
            validatecommand=(self.register(self._validate), "%P")
        )
        self.populationSpin.pack(side="top", pady=5)

    def _validate(self, P):
        return P.isdigit()
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685