How do I save a value in an external variable? How do I save a value in an external variable? tkinter tkinter

How do I save a value in an external variable?


From googling tk.Label it looks like the idea of textvariable is that it refers to a mutable tk.StringVar, not a normal Python str (which is immutable). Hence all you need to do is declare the StringVar in the outer scope and then update it inside the callback:

    date = tk.StringVar()    def set_date():         date.set(cal.get_date())    ttk.Button(top, text="Aceptar", command=set_date).pack()     labelFecha = Label(root, textvariable=date)


You're not using the textvariable- option properly. You need to set it a reference to an instance of a tk.StringVar variable class. Afterwards any changes to the variable's value will automatically update what the widget displays.

Also note that the tkcalendar.DateEntry.get_date() method returns a datetime.date, not a string, so you'll need manual to convert it into one yourself before setting the StringVar's value to it.

Here's a runnable example illustrating what I am saying:

import tkinter as tkimport tkinter.ttk as ttkfrom tkcalendar import DateEntrydef dateentry_view():    def print_sel():        date = cal.get_date()  # Get datetime.date.        fechaStr = date.strftime('%Y-%m-%d')  # Convert datetime.date to string.        fechaVar.set(fechaStr)  # Update StringVar with formatted date.        top.destroy()  # Done.    top = tk.Toplevel(root)    ttk.Label(top, text='Elige el día').pack()    cal = DateEntry(top)    cal.pack(padx=10, pady=10)    ttk.Button(top, text="Aceptar", command=print_sel).pack()root = tk.Tk()ttk.Button(root, text="Ejecutar prueba", command=dateentry_view).pack()fechaVar = tk.StringVar(value='<no date>')  # Create and initialize control variable.labelFecha = tk.Label(root, textvariable=fechaVar)  # Use it.labelFecha.pack()root.mainloop()