Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an Integer from Entry

Tags:

python

tkinter

How do I get an integer type from the Tkinter Entry widget?

If I try to get the value using variable_name.get(), it says it is a str. If I try to change the type using int(variable_name.get()), it says int can only accept a string or number.

Any help would be welcome!

like image 342
Paris Avatar asked Nov 16 '10 21:11

Paris


People also ask

How do you get integer input from user in Python?

As we know that Python's built-in input() function always returns a str(string) class object. So for taking integer input we have to type cast those inputs into integers by using Python built-in int() function.

How do I get data from the entry box in Python?

To return the data entered in an Entry widget, we have to use the get() method. It returns the data of the entry widget which further can be printed on the console.

What is Tk StringVar ()?

StringVar() is a class from tkinter. It's used so that you can easily monitor changes to tkinter variables if they occur through the example code provided: def callback(*args): print "variable changed!" var = StringVar() var.trace("w", callback) var. set("hello")

How do you print an integer in Python?

Use the print() function to print an integer value, e.g. print(my_int) . If the value is not of type integer, use the int() class to convert it to an integer and print the result, e.g. int(my_str) .


1 Answers

In the end I just initialized the variable as tk.IntVar() instead of tk.StringVar()

That way you don't have to cast it as an int, it will always be one, and the default value from the Entry element will now be 0 instead of ''

That's how I approached it anyway, seems the simplest way and avoid the need for a lot of the validation you'd need to do otherwise...

like image 56
user3429497 Avatar answered Sep 17 '22 09:09

user3429497