Home > Software engineering >  Cannot change entry value to integer in tkinter
Cannot change entry value to integer in tkinter

Time:10-12

I tried to change the input to an integer using int(e.get()), but it gave this error:

Exception has occurred: ValueError (note: full exception trace is shown but execution is paused at: ) invalid literal for int() with base 10: ''

This is my code. Look under #call_duration.


from tkinter import *
root =Tk()
root.title("Carbon Emission Calculator")
root.geometry("2560x1600")


#main title
main_title = Label(root, text="Carbon Emissions from Zoom Calls", font="Arial 25").pack(pady=75, padx=0)


#defining selections for radio buttons
x = IntVar()
y = IntVar()


#type of call
type_of_call = Label(root, text="Number of participants", font="Arial 20").pack(pady = 10)
Radiobutton(root,text= "1:1 call", variable= x, value=1).pack()
Radiobutton(root,text= "Group call", variable= x, value=2).pack()


#call quality
call_quality = Label(root, text="Call Quality", font="Arial 20").pack(pady = (40,10))
Radiobutton(root,text= "Default", variable= y, value=1).pack()
Radiobutton(root,text= "720p HD", variable= y, value=2).pack()
Radiobutton(root,text= "1080p HD", variable= y, value=3).pack()


#call duration
duration_of_call = Label(root, text="Duration of Call (in hours)", font="Arial 20").pack(pady = (40,10))
e = Entry(root, width = 10)
e.pack(pady = (0,40))

sample_value = int(e.get())




#calculations are here
#if (x.get() == 1):
    #if y.get = 




#submit button!
def onclick():
    text = Label(root, text= sample_value).pack()

submit_button= Button(root, text="Calculate", command = onclick).pack()



root.mainloop()

CodePudding user response:

To get value from an Entry when you need, you need to set up a callback that will do it. This callback has to be triggered by some event, it could be pressing the button (command argument) or some bound sequence (entry.bind('<Return>', lambda e: print(int(e.widget.get())))):

from tkinter import Tk, Entry, Button


def convert_to_int():
    value = entry.get()
    if not value:
        return
    value = int(value)
    print(value)


def validate_integer(character):
    return True if character in '1234567890' else False


root = Tk()

validate_integer_tk = root.register(validate_integer)
entry = Entry(
    root, validate='key', validatecommand=(validate_integer_tk, '%S')
)
entry.pack(fill='both', expand=True)

btn = Button(root, text='Print Number', command=convert_to_int)
btn.pack(fill='both', expand=True)

root.mainloop()

Here a button is used, when the user clicks the button it calls the convert_to_int function and then it gets value from the entry (if there is no value (if it is an empty string) it will stop the function), then it converts it to an integer.

Another crucial part is the validatecommand because it allows users to only put numbers in the entry

Sources:

  • Related