How to check if the contents of an entry widget in python/tk is a float, string, boolean or integer?

tkinter entry validate
tkinter entry default value

I am trying to check whether users' input to a Tk GUI I created is of the right data type I wanted it to be (integer), but I have only been able to check whether their input is a Boolean, and I need to check whether their input is a string or an integer as well:

from tkinter import*

# creates a GUI
Tester = Tk()

NonEssentialFoodEntry = Entry(Tester, width="30")

NonEssentialFoodEntry.place(x=300,y=540)

def checker():
     if NonEssentialFoodEntry.get() == 'TRUE' or 'FALSE':
            tkinter.messagebox.showerror("","You have entered a boolean value in the Non-EssentialFood entry field, please enter an integer")


Checker=Button(Tester, height="7",width="30",font=300,command=checker)

Checker.place(x=700, y=580)

Well, you could run a regular expression on the input and check which group is not None:

(?:^(?P<boolean>TRUE|FALSE)$)
|
(?:^(?P<integer>\d+)$)
|
(?:^(?P<float>\d+\.\d+)$)
|
(?:^(?P<string>.+)$)

See a demo on regex101.com. In the first place, every input is a string though.


In Python:

import re
strings = ["TRUE", "FALSE", "123", "1.234343", "some-string", "some string with numbers and FALSE and 1.23 in it"]

rx = re.compile(r'''
    (?:^(?P<boolean>TRUE|FALSE)$)
    |
    (?:^(?P<integer>-?\d+)$)
    |
    (?:^(?P<float>-?\d+\.\d+)$)
    |
    (?:^(?P<string>.+)$)
    ''', re.VERBOSE)

for string in strings:
    m = rx.search(string)
    instance = [k for k,v in m.groupdict().items() if v is not None]
    print(instance)
    if instance:
        print("{} is probably a(n) {}".format(string, instance[0]))

As said in the comments above your original question you might follow another way with try/except though.

Python Tkinter - Validating Entry Widget, Skip to content Tkinter or Tk interface is one of the most widely used Python interface to build The callback function checks the input in the Entry widget for valid entry. In this example, the input entered through the keyboard is checked for register() method returns a string which is assigned to a variable 'reg' that is � Returns the entry's current text as a string. 3: icursor ( index ) Set the insertion cursor just before the character at the given index. 4: index ( index ) Shift the contents of the entry so that the character at the given index is the leftmost visible character. Has no effect if the text fits entirely within the entry. 5: insert ( index, s )

One approach to this is to try to convert your input and see if it manages.

EDIT: this is basically the approach suggested by @martineau in the comments

The following code is adapted from FlyingCircus (Disclaimer: of which I am the main author):

def auto_convert(
    text,
    casts=(int, float, complex)):
"""
Convert value to numeric if possible, or strip delimiters from string.

Args:
    text (str|int|float|complex): The text input string.
    casts (Iterable[callable]): The cast conversion methods.

Returns:
    val (int|float|complex): The numeric value of the string.

Examples:
    >>> auto_convert('<100>', '<', '>')
    100
    >>> auto_convert('<100.0>', '<', '>')
    100.0
    >>> auto_convert('100.0+50j')
    (100+50j)
    >>> auto_convert('1e3')
    1000.0
    >>> auto_convert(1000)
    1000
    >>> auto_convert(1000.0)
    1000.0
"""
if isinstance(text, str):
    val = None
    for cast in casts:
        try:
            val = cast(text)
        except (TypeError, ValueError):
            pass
        else:
            break
    if val is None:
        val = text
else:
    val = text
return val

Note that you would need a specialized function for the Boolean case, since bool(text) will evaluate to True as soon as text is non-empty (which is also present in the latest version of FlyingCircus as flyingcircus.util.to_bool()).

GUI Programming with Python: Variable Classes in Tkinter, Tutorial on TKinter under Python: Introducing Variable Classes: StringVar, IntVar, DoubleVar Some widgets (like text entry widgets, radio buttons and so on) can be x = StringVar() # Holds a string; default value ""; x = IntVar() # Holds an integer; a float; default value 0.0; x = BooleanVar() # Holds a boolean, returns 0 for� 1 How to check if the contents of an entry widget in python/tk is a float, string, boolean or integer? Feb 22 '19 0 How to compare data contained and retrieved from entry widgets with data retrieved from an SQL database in python?

For instance you could use the following code to build an if-statement around a valid integer: if isinstance(<var>, int): Otherwise get the type with type(<var>) and build your functions around it.

The Variable Classes (BooleanVar, DoubleVar, IntVar, StringVar), If you program Tk using the Tcl language, you can ask the system to let you know when Variables can also be used to validate the contents of an entry widget, and to multiple Tk instances (which you shouldn't do, unless you really know what you're doing). For DoubleVar variables, the returned value is a Python float. Entry Widget issue: PA3040: 13: 675: Mar-06-2020, 10:24 AM Last Post: Larz60+ Transfer Toplevel window entry to root window entry with TKinter: HBH: 0: 1,136: Jan-23-2020, 09:00 PM Last Post: HBH : The coordinates of the Entry widget (canvas) when moving: berckut72: 8: 702: Jan-07-2020, 09:26 AM Last Post: berckut72 [Tkinter] Entry widget to

tkinter.ttk — Tk themed widgets — Python 3.8.5 documentation, That code causes several tkinter.ttk widgets ( Button , Checkbutton , Entry If set to the empty string (the default), the cursor is inherited for the parent When the view in the widget's window change, the widget will generate a Tcl Specifies an integer value indicating the desired width of the entry window, Float value. If� Entry widgets are the basic widgets of Tkinter used to get input, i.e. text strings, from the user of an application. This widget allows the user to enter a single line of text. If the user enters a string, which is longer than the available display space of the widget, the content will be scrolled.

15.8. Tkinter Standard Dialog Boxes — How to Think like a , You can refer to the Python documentation for additional optional parameters. The return value is a Boolean, True or False, answer to the question. If 15.8.3. Single Value Data Entry�. If you want to ask the user for a single data value, either a string, integer, answer = simpledialog.askfloat("Input", "What is your salary? Tkinter supports some variables which are used to manipulate the values of Tkinter widgets. These variables work like normal variables. set() and get() methods are used to set and retrieve the values of these variables.

Entry widgets, The Entry widget is a simple, single-line text input field. It is typically used for input fields in form-like dialogs, and anywhere else you need the user PP2E\ Gui\Tour>python entry1.py Input => "Type words here" Input => "Have a cigar" and integer 0 and string '0' mean the same thing (Tkinter method arguments are always� For DoubleVar variables, the returned value is a Python float. For IntVar, it’s an integer. For StringVar, it’s either an ASCII string or a Unicode string, depending on the contents. The set method updates the variable, and notifies all variable observers. You can either pass in a value of the right type, or a string.

Comments
  • have you tried using isinstance(value, float) to verify if the value is a float?
  • @akhavro: Can't do that because Entrys can only contain sting values.
  • The problem is that 1 is a valid integer (number 1), a valid float (1.0), a valid string ('1') and can be implicitely converted to True in a boolean context. You are trying to handle the thing the wrong side: do not try to guess what an entry is, just check that it can be converted to the expected type.
  • right. Then regex is your solution, as @Jan answered ;)
  • user9156115: A common way to do that in Python is to use try/except and attempt to convert the string value into each type and see if it works. i.e. something along the line of" try, float(entry.get()), except ValueError:. Note that the order of testing matters because some values might be able to be converted to more that one type.