How to get a number as Input in Tkinter?
- tinyytopic.com
- 0
- on Mar 21, 2023
How to get a number as Input in Tkinter using Python ready-to-use function?
This Python function gets input from the user using the Tkinter input window. Ready-to-use Python function to get an Integer or Float number:
def get_number_input(header, prompt, root, number_type):
# Get an Integer number
if number_type == 'integer' or number_type == 'Integer' or number_type == 'int' or number_type == 'Int':
while True:
try:
number_str = simpledialog.askinteger(header, prompt, parent=root)
break
except ValueError:
print("That's not an integer. Please try again.")
number_str = None
return number_str
# Get a float number
elif number_type == 'float' or number_type == 'Float':
while True:
try:
number_str = simpledialog.askfloat(header, prompt, parent=root)
break
except ValueError:
print("That's not a float. Please try again.")
number_str = None
return number_str
Write your main code as a sample below,
header = 'Number Entry'
prompt = 'Enter an Integer number: '
number_type = 'Integer'
number = get_number_input(header, prompt, root, number_type)
print(number)
or
header = 'Number Entry'
prompt = 'Enter a decimal number: '
number_type = 'Float'
number = get_number_input(header, prompt, root, number_type)
print(number)
A Sample Integer Output:
150
A Sample Decimal Output:
12.35
How does the function work?
This is a Python function called get_number_input that accepts four parameters: header, prompt, root, and number_type. Here’s how it works:
- The function starts by checking whether the
number_typeparameter is set to'integer','Integer','int', or'Int'. If it is, the function uses awhileloop to repeatedly ask the user for an integer input using thesimpledialog.askintegerfunction. If the user enters a value that cannot be converted to an integer, aValueErrorexception is raised, and the loop continues. Once the user enters a valid integer, the function returns that integer value. - If the
number_typeparameter is set to'float'or'Float', the function uses a similarwhileloop to ask the user for a float input using thesimpledialog.askfloatfunction. Again, if the user enters a value that cannot be converted to a float, aValueErrorexception is raised, and the loop continues. Once the user enters a valid float, the function returns that float value. - If the
number_typeparameter is not set to'integer','Integer','int','Int','float', or'Float', the function does not do anything and simply returnsNone.
Overall, this function can be used to get either an integer or a float input from the user, depending on the value of the number_type parameter. If the user enters an invalid value, the function will continue to prompt them until they enter a valid one.