Home > Back-end >  How to cast string to integer in Tkinter python
How to cast string to integer in Tkinter python

Time:09-21

How to cast string from the entry box to integer in Tkinter. I've tried this but it doesn't work.

import tkinter 
from tkinter import tt

age= tkinter.Label(window, text = "How old are you?")
age.grid(row = 1, column = 0)

entry_age = tkinter.Entry(window)
Entry.grid(row = 1, column = 1)

height = tkinter.Label(window, text = "What is your height(cm): ")
height.grid(row = 2, column = 0)

entry_height = tkinter.Entry(window)
entry_height.grid(row = 2, column = 1)

weight = tkinter.Label(window, text = "your weight (kg): ")
weight.grid(row = 3, column = 0)

entry_weight = tkinter.Entry(window)
entry_weight.grid(row = 3, column = 1) 

entry_age1 = entry_age.get()

entry_age1 = int(entry_age1)


entry_heigh1t = entry_height.get()

entry_height1 = int(entry_height1)

entry_weight1 = entry_weight.get()

entry_weight1 = int(entry_weight1)

CodePudding user response:

Here .get() function always return anything as a string. You have to convert that into str to int.

Here is the quick example.

import tkinter as tk

win = tk.Tk()

def get_number():
    text = ent.get()
    try:
        num = int(text)    # <= Focus here
        print(num)
    except:
        print("This is not number")

ent = tk.Entry(win)
ent.grid(row=0, column=0, padx=10, pady=10)

btn = tk.Button(win, text="Get Number", command=get_number)
btn.grid(row=1, column=0)

win.mainloop()

CodePudding user response:

I don't see anything wrong with your code just by looking at what you've posted. Please post the error message you're getting along with some test cases as input for the Entry boxes.

entry_age.get() returns a string that can be converted into an integer using int() if the input is a number of course.

Edit after @Milena Pavlovic replied with the error:

The program won't run because as soon as it runs the statement entry_age1 = entry_age.get() which stores the empty string into the variable, the next statement that follows tries to convert this empty string into an integer. Empty strings go by "" which cannot be converted to integer type. Since this is invalid, it raises the value error. To resolve this, you can make the following changes:

entry_age1 = entry_age.get()

if entry_age1.isdecimal():
    entry_age1 = int(entry_age1)

entry_height1 = entry_height.get()

if entry_height1.isdecimal():
    entry_height1 = int(entry_height1)

entry_weight1 = entry_weight.get()

if entry_weight1.isdecimal():
    entry_weight1 = int(entry_weight1)

The isdecimal() function checks if the string returned by get() is a decimal and only then will it get converted into an integer and stored into the respective variables and allow you to do what you want with them.

  • Related