0

I made a simple piece of code with Python using the tKinter library. I want to check whether user input is a number using a simple function with try and except ValueError. For some reason, it only shows the text that is supposed to be printed when the input is not a number. The message that should appear once the button is pressed is stored in the feedback variable So the problem is this: How can I make it so it does not give the "This is not a number" print on the screen by default, but instead an empty screen with the right text once the save button is pressed.

def number_input():
    root=Tk()
    root.geometry(400x400)
    
    rounds=Entry(root)
    
    feedback=Label(root, text='')
    feedback.place(relx=0.5, rely=0.8, anchor=CENTER)
    
    save=Button(root, height=1, width=10, text='save', command=number())
    save.place(relx=0.5, rely=0.72, anchor=CENTER)

This is the function for the try and except part:

def number():
    try:
        int(rounds.get())
        feedback.config(text='This is a number')
    except ValueError:
        feedback.config(text='This is not a number')
Beaver
  • 1
  • 5
  • Change `command=number()` to `command=number` – TheLizzard Mar 11 '21 at 22:32
  • You are actually calling `number()` during the creation of your button - which of course displays the error message because the user has had no chance to enter anything. You just want `command=number`. – jasonharper Mar 11 '21 at 22:33
  • @TheLizzard A simple but yet effective change. This fixed the entire problem – Beaver Mar 11 '21 at 22:33
  • Also you need to change `root.geometry(400x400)` to `root.geometry("400x400")` and you need to `.place` your entry somewhere on your screen. – TheLizzard Mar 11 '21 at 22:38

1 Answers1

0

Your code:

save = Button(..., command=number())

That calls the number function and sets the command to the result from that function which is None. What you want to do is:

save = Button(..., command=number)

That passes the function to tkinter so it can call it when you press the button.

TheLizzard
  • 7,248
  • 2
  • 11
  • 31