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!
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.
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.
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")
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) .
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With