Python entry input verification

109 views Asked by At

I want to create a simple game in Python 3.8, and i need to verify an entry`s input in order to create it. Something like this:

 if input.text == "":
      print("Error")

but i don`t know how to do this in Python. I used to do that a lot in C# but here it s not that easy apparently.

2

There are 2 answers

0
Mike - SMT On

Considering you are talking about an Entry and also have the Tag tkinter in your question I assume you want to get some user input from a tkinter Entry widget.

To get a value from a Entry widget you can use the get() method. This returns a string. You can use a simple button command or a bind() to call a function that then checks the value of the entry field.

You can also throw in a strip() just in case the user uses a space or two without imputing anything else. This way a string of spaces still returns back as an error.

Here is a simple example:

import tkinter as tk


def check_entry():
    value = entry.get().strip()
    if value == '':
        print('Error')
    else:
        print('Value is not an empty string. Now do something.')


root = tk.Tk()
entry = tk.Entry(root)
entry.pack()
tk.Button(root, text='Check Entry', command=check_entry).pack()
root.mainloop()
1
Ayush Garg On

To get an input, you can use the input function. This will automatically return a string. Here is sample usage of this:

user_input = input("Please put your input here: ") # Get user input
if user_input == "": # Compare input to empty string
    print("Error")

You can see the Python docs for more information about input.