我如何从 def cal_fun() 调用变量 c

How do i call variable c from def cal_fun()

我试图在下面的代码中调用变量 c。它说 cal 未定义

def pay_cal():

    def cal_fun():
        t = Toplevel()
        global cal
        cal = Calendar(t, year=2019, month=6, day=1, foreground='Blue', background='White', selectmode='day')
        cal.pack()

    c = cal.get_date

    sub_win =Tk()
    sub_win.geometry('400x500+600+100')
    sub_win.title('Payout Calculator')

    l1 = Button(sub_win, text= 'Check-In Date:', command= cal_fun)
    chck_in_date = Label(sub_win, textvariable= c )
    l1.grid(row=1)
    chck_in_date.grid(row=1, column=2)

您的代码有几处错误。对于初学者,当 cal 尚未创建时,您将 c 定义为 cal.get_date

接下来,您将 c 作为 textvariable 传递给 label 小部件。它不会引发任何错误,但也不会更新 - 您需要的是一个 StringVar 对象。

您还缺少根据日历选择更新文本变量的机制。即使您的原始代码是固定的,日期也只会在执行时更新一次。

以下是让一切正常运行的方法:

from tkinter import *
from tkcalendar import Calendar #I assume you are using tkcalendar

def pay_cal():

    def cal_fun():
        t = Toplevel()
        global cal
        cal = Calendar(t, year=2019, month=6, day=1, foreground='Blue', background='White', selectmode='day')
        cal.pack()
        cal.bind("<<CalendarSelected>>",lambda e: c.set(cal.get_date())) #make use of the virtual event to dynamically update the text variable c

    sub_win = Tk()
    sub_win.geometry('400x500+600+100')
    sub_win.title('Payout Calculator')
    c = StringVar() #create a stringvar here - note that you can only create it after the creation of a TK instance

    l1 = Button(sub_win, text= 'Check-In Date:', command= cal_fun)
    chck_in_date = Label(sub_win, textvariable=c)
    l1.grid(row=1)
    chck_in_date.grid(row=1, column=2)
    sub_win.mainloop()

pay_cal()

最后我注意到您使用 sub_win 作为此函数的变量名 - 这意味着您可能有一个 main_win 其他名称。通常不建议使用 Tk 的多个实例 - 如果您需要额外的 windows,只需使用 Toplevel.