1

I need the user to enter an integer number into my program. They shouldn't be able to enter strings/floats. If the user hasn't entered an integer and clicks the button I would like an error message to pop up similar to the one you get if your username/password is incorrect when logging into something.

from tkinter import *

class GUI:
    def __init__(self, parent):
        self.iv = IntVar()
        self.sb = Spinbox(parent, from_=0, to=10, textvariable = self.iv)
        self.sb.pack()
        self.b1 = Button(parent, text="Confirm")
        self.b1.pack()

root = Tk()
root.geometry("800x600")
GUI = GUI(root)
root.title("Example")
root.mainloop()
j_4321
  • 15,431
  • 3
  • 34
  • 61
Blue_Wolf13
  • 15
  • 1
  • 2
  • 6

3 Answers3

2

The spinbox supports input validation in exactly the same way as the Entry widget. You can set up a validatecommand that will only allow digits to be entered.

For example:

class GUI:
    def __init__(self, parent):
        ...
        # add validation to the spinbox
        vcmd = (parent.register(self.validate_spinbox), '%P')
        self.sb.configure(validate="key", validatecommand=vcmd)

    def validate_spinbox(self, new_value):
        # Returning True allows the edit to happen, False prevents it.
        return new_value.isdigit()

For more information on input validation see Interactively validating Entry widget content in tkinter

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
2

You may use the option state = 'readonly'. This option applies to Spinbox and Combobox also. With this option setted the user can only choose from the values you provided.

Dragos
  • 21
  • 1
0

Here is the code corresponding to Splinxyy suggestion: convert the spinbox content with int() inside a try/except block

from tkinter import *
from tkinter.messagebox import showerror

class GUI:
    def __init__(self, parent):
        self.iv = IntVar()
        self.sb = Spinbox(parent, from_=0, to=10, textvariable = self.iv)
        self.sb.pack()
        self.b1 = Button(parent, text="Confirm", command=self.validate)
        self.b1.pack()

    def validate(self):
        nb = self.sb.get()
        try:
            nb = int(nb)
            # do something with the number
            print(nb)
        except Exception:
            showerror('Error', 'Invalid content')


root = Tk()
root.geometry("800x600")
GUI = GUI(root)
root.title("Example")
root.mainloop()
j_4321
  • 15,431
  • 3
  • 34
  • 61