pythondatedatetimetkintertkcalendar

How do I save a value in an external variable?


The doubt was the following, I want to select a date using the tkcalendar library, it is selected correctly, but I cannot use the variable outside the function.

def dateentry_view():
    def print_sel():
        date = cal.get_date()
        print(date)
    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()

How can I pass the date variable to display it in a Label as follows:

labelDate = Label(root,textvariable=date)

I have tried to put the Label inside the function, but it still doesn't show the date variable.

def dateentry_view():
    
    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() 

    def print_sel():
         date = cal.get_date()
         print(date)
         labelFecha = Label(root,textvariable=date)

When I print date it shows me the date I have selected correctly.


Solution

  • 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)