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

时间:2019-06-10 19:05:12

标签: python-3.x tkinter calendar nameerror nested-function

我正在尝试在以下代码中调用变量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)

1 个答案:

答案 0 :(得分:0)

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

接下来,您将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的多个实例-如果需要其他窗口,只需使用Toplevel