Save a get () in a variable

0

I am programming in Python3 with tkinter and when I try to save the result of a text box (an Entry) in a .get () and use that variable in a Label, it does not appear, for example:

varNum=IntVar()
cadrotexto=Entry(root)
numeroRecogido=cuadrotexto.get()

miLabel=Label("Escogiste el número:" + numeroRecogido)

Is this how I declare a variable as numeric and this is how to save the value of Entry in a variable?

    
asked by user96431 14.09.2018 в 16:06
source

1 answer

0

First you must take into account that when you do:

numeroRecogido=cuadrotexto.get()

you effectively get the content of the Entry as a string at that moment and this chain is associated with the variable numeroRecogido . If you later modify the Entry the variable will not change for that reason.

The call to get must occur at the instant you want to get the content of the Entry , not just after the initialization of the widget, because you will get an empty string as is logical. If you use a button to process what is entered in Entry , the reading of it must be within the callback associated with the button.

On the other hand, you can associate a StringVar with both the Label and the Entry , which if modified when the content of the widget is and vice versa. You can associate a IntVar with Entry , but an exception will be thrown if the entry is not convertible to an integer.

An example:

import tkinter as tk


def aceptar():
    try:
        n = int(var_texto.get())  # Obtenemos el número de la StringVar
    except ValueError:            # Si lo ingresado no es un entero
        var_lbl.set(f"No escogiste un número válido")
    else:                         # Si lo ingresado es un entero
        var_lbl.set(f"Escogiste el número: {n}")


root = tk.Tk()

var_texto = tk.StringVar()
var_lbl = tk.StringVar()

mi_label = tk.Label(root, textvariable=var_lbl)
var_lbl.set("Escoge un número") # Contenido inicial del Lable
mi_label.grid(row=0, column=0, columnspan=3)

cuadro_texto = tk.Entry(root, textvariable=var_texto)
cuadro_texto.grid(row=1, column=0, columnspan=2)

btn_aceptar = tk.Button(root, text="Aceptar", command=aceptar)
btn_aceptar.grid(row=1, column=2)

root.mainloop()
    
answered by 14.09.2018 в 18:34