【问题标题】:How do I save a value in an external variable?如何将值保存在外部变量中?
【发布时间】:2021-03-27 19:33:19
【问题描述】:

疑问如下,我想使用tkcalendar库选择一个日期,它选择正确,但我不能在函数外使用变量。

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 放入函数中,但它仍然没有显示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 时,它会显示我正确选择的日期。

【问题讨论】:

  • 了解 Python 关键字 globalnonlocal
  • global/nonlocal 这里不需要!每当您使用这些关键字时,您可能让自己承受痛苦。
  • @MichaelButscher 从来不知道有 nonlocal 关键字。介意解释一下吗?
  • @TheLizzard:您可以在documentation 中了解它。

标签: python date datetime tkinter tkcalendar


【解决方案1】:

从谷歌搜索tk.Label 看起来textvariable 的想法是它指的是可变的tk.StringVar,而不是普通的Python str(它是不可变的)。因此,您需要做的就是在外部范围内声明 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)

【讨论】:

    【解决方案2】:

    您没有正确使用textvariable- 选项。您需要将其设置为对tk.StringVar 变量类的实例的引用。之后对变量值的任何更改都会自动更新小部件显示的内容。

    还要注意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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-06
      • 2012-01-04
      • 2019-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多