簡體   English   中英

如何將值保存在外部變量中?

[英]How do I save a value in an external variable?

疑問如下,我想使用tkcalendar庫為 select 一個日期,它選擇正確,但我不能使用 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()

如何傳遞date變量以將其顯示在Label中,如下所示:

labelDate = Label(root,textvariable=date)

我試圖將Label放在 function 中,但它仍然沒有顯示date變量。

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)

當我打印date時,它會顯示我正確選擇的日期。

從谷歌搜索tk.Label看起來textvariable的想法是它指的是可變的tk.StringVar ,而不是普通的 Python str (它是不可變的)。 因此,您需要做的就是在外部 scope 中聲明StringVar ,然后在回調中更新它:

    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)

您沒有正確使用textvariable-選項。 您需要將其設置為對tk.StringVar變量 class 實例的引用。 之后對變量值的任何更改都會自動更新小部件顯示的內容。

另請注意, tkcalendar.DateEntry.get_date()方法返回datetime.date ,而不是字符串,因此您需要手動將其轉換為自己,然后再將StringVar的值設置為它。

這是一個可運行的示例,說明了我在說什么:

import tkinter as tk
import tkinter.ttk as ttk
from tkcalendar import DateEntry


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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM