【问题标题】:How do i call variable c from def cal_fun()我如何从 def cal_fun() 调用变量 c
【发布时间】:2019-06-10 19:05:12
【问题描述】:

我试图在下面的代码中调用变量 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)

【问题讨论】:

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


    【解决方案1】:

    您的代码存在一些问题。对于初学者,当 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 的多个实例 - 如果您需要额外的窗口,只需使用Toplevel

    【讨论】:

    • 如果有帮助,请考虑接受答案,以便关闭问题。
    • 我有一个小问题,我在下面的代码中提到了,你能帮忙吗?
    • 如果您有新问题,您应该作为新问题发布,而不是添加为答案。话虽如此,我无法理解您的任何新代码或您想要实现的目标。
    猜你喜欢
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多