Entry method in Tkinter, Python

Asked

Viewed 304 times

-1

Hello, I was trying to get one the numerical value of the Entry method, I got it, with get(), but when turning to float or int, depending on where this one returns me an error. The way it works, right, but I would like to understand, why the error if I try to convert to a float or int, just below the entry, ex in the code below, where this comentad(teste3 = float(teste2)), at this error location, but if I call the function in ttk.Bunton, not the error.

this is the mistake that gives:

teste3 = float(teste2) ValueError: could not convert string to float:

''

''' python


import tkinter as tk

from tkinter import ttk

def imprime():

    valor2 = valor.get()

    valor2 = float(valor2)


win = tk.Tk()


win.title("Calculadora Simples")

label = ttk.Label(win, text="digite um numero")

label.grid(column=0, row=0)


valor = ttk.Entry(win)

valor.grid(column=1, row=0)

teste2 = valor.get()

#===========================================
#teste3 = float(teste2)
#===========================================

action = ttk.Button(win, text="Click me", command=imprime)

action.grid(column=1, row=1)
#=====================
# Start GUI
#=====================
win.mainloop()

1 answer

0

The error occurs because the return of valor.get() is empty, soon while trying to convert empty to float, you have conversion error, it is possible to simulate this same situation with the code below:

valor = float("")

You can convert the value, only if the get something back, making a simple if:

if teste2:
    teste3 = float(teste2)
else:
    teste3 = 0

But stay tuned, not every value can be converted to float, if the user type letters in your Entry, clicking the button will also generate an error.

In this case, an option is to check the exception during the conversion:

try:
  valor = float("A")
except ValueError:
  valor = 0

print(valor)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.