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

标签 python calendar tkinter ttk

ttk calendar class基于 tkinter 制作日历。如何让它返回所选日期的值?以下是我尝试过的,它返回“NoneType 对象不可调用”:

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()

最佳答案

选择是一个@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

关于python 日历小部件 - 返回用户选择的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27774089/

相关文章:

android - 如何使用 Google 日历用于我的 Android 应用程序的日期选择器?

python - 为什么 tkfont.Font().measure 返回大值?

python - 带有列表的列中按字符串的 pandas df 子集

python - 将矩阵中的值与阈值进行比较并创建超出阈值的列表

r - 按 id 为多个日期之间的每个日期创建行

Python 2.7 - ttk 模块似乎无法在 Windows 8.1 中运行

python - 如何更改标签内某些单词的颜色?

python - 男人脸和女人脸的区别

python - UnboundLocalError:分配前已引用本地变量“已按下”

android - 将日历对象添加到 ParseObject