python日历小部件-返回用户选择的d

2024-05-11 14:25:54 发布

您现在位置:Python中文网/ 问答频道 /正文

这个ttk calendar class制作了一个基于tkinter的日历。如何使它返回所选日期的值?下面是我尝试的,它返回了“NoneType object is not callable”:

def test():
    import sys
    root = Tkinter.Tk()
    root.title('Ttk Calendar')
    ttkcal = Calendar(firstweekday=calendar.SUNDAY)
    ttkcal.pack(expand=1, fill='both')

    x = ttkcal.selection()  #this and the following line are what i inserted
    print 'x is: ', x  #or perhaps return x

    if 'win' not in sys.platform:
        style = ttk.Style()
        style.theme_use('clam')
    root.mainloop()

if __name__ == '__main__':
    test()

Tags: testifobjectisstyletkintersysnot
1条回答
网友
1楼 · 发布于 2024-05-11 14:25:54

选择是一个@property,因此需要执行以下代码:

x = ttkcal.selection

此外,使用此日历,您可以在关闭callendar小部件(即mainloop()之后)之后获取所选日期。因此,您的代码应该是:

def test2():
    import sys
    root = Tkinter.Tk()
    root.title('Ttk Calendar')
    ttkcal = Calendar(firstweekday=calendar.SUNDAY)
    ttkcal.pack(expand=1, fill='both')

    if 'win' not in sys.platform:
        style = ttk.Style()
        style.theme_use('clam')

    root.mainloop()

    x = ttkcal.selection    
    print 'x is: ', x  

以防万一。如果不想关闭日历窗口以获取所选值,但希望在单击时“实时”获取这些值,例如在其他窗口的标签中显示它们,则可以执行以下操作:

首先扩展Calendar类以添加每次选择某个日期时将调用的回调函数:

class Calendar2(Calendar):
    def __init__(self, master=None, call_on_select=None, **kw):
        Calendar.__init__(self, master, **kw)
        self.set_selection_callbeck(call_on_select)

    def set_selection_callbeck(self, a_fun):
         self.call_on_select = a_fun


    def _pressed(self, evt):
        Calendar._pressed(self, evt)
        x = self.selection
        #print(x)
        if self.call_on_select:
            self.call_on_select(x)

通过这个,您可以创建新的test2示例,它有两个窗口。一个用于日历,另一个带有标签的窗口(例如):

class SecondFrame(Tkinter.Frame):

    def __init__(self, *args, **kwargs):
        Tkinter.Frame.__init__(self, *args, **kwargs)
        self.l = Tkinter.Label(self, text="Selected date")
        self.l.pack()
        self.pack()

    def update_lable(self, x):
        self.l['text'] = x;



def test2():
    import sys
    root = Tkinter.Tk()
    root.title('Ttk Calendar')


    ttkcal = Calendar2(firstweekday=calendar.SUNDAY)
    ttkcal.pack(expand=1, fill='both')

    if 'win' not in sys.platform:
        style = ttk.Style()
        style.theme_use('clam')           


    sf = SecondFrame(Tkinter.Toplevel())

    ttkcal.set_selection_callbeck(sf.update_lable)        

    root.mainloop()

在本例中,每当您在日历中选择某个日期时,SecondFrame中的标签都将更新。

enter image description here

相关问题 更多 >