2014-10-02 60 views
1

我有thisttk日历和我的程序是为了在日历小部件中的日期被按下时更新字段。TTKCalendar选择返回Python

这里是start_dateend_date领域:

start_date = StringVar() 
start_date = ttk.Entry(f2, width=15, textvariable=start_date) 
start_date.grid(column=2, row=1, sticky=E) 

ttk.Label(f2, text="Start date:", width=10).grid(column=1, row=1, sticky=E) 

end_date = StringVar() 
end_date = ttk.Entry(f2, width=15, textvariable=end_date) 
end_date.grid(column=2, row=2, sticky=E) 

ttk.Label(f2, text="End date:", width=10).grid(column=1, row=2, sticky=E) 

下面是按钮触发功能:

def callbackCal(): 
    root2=Toplevel(f2) 
    ttkcal = ttkcalendar.Calendar(root2,firstweekday=calendar.SUNDAY) 
    ttkcal.pack(expand=1, fill='both') 
    root2.update() 
    root2.minsize(root2.winfo_reqwidth(), root2.winfo_reqheight()) 

这里的按钮代码:

b=ttk.Button(f2, width=4, text="Cal", command=callbackCal).grid(column=3,row=1, sticky=W) 

感谢NorthCat's的帮助,我能够远远得到这个。我知道ttk日历的方法_pressed(),_show_selection()和selection()。但我不知道如何使用它们来显示点击时的选定日期。而且,一旦完成,关闭日历小部件。

非常感谢!并为这些新手问题感到抱歉。

回答

1

我不假装理解代码,但是我发现一个问题的答案提出了一些变化的另一个问题,得到的答复是从kalgasnik

Python tkinter with ttk calendar

然后我做了这个变化: -

def __init__(self, master=None, selection_callback=None, **kw): 

并加入此在初始化功能

 self.selection_callback = selection_callback 

在_pressed功能我加

 if self.selection_callback: 
      self.selection_callback(self.selection) 

基本上添加的回调被点击的日期时,得到的值。

我的示例回调程序为: -

import calendar 
import tkinter as TK 
import tkinter.font 
from tkinter import ttk 
from ttk_calendar import Calendar 
import sys 


class Test(): 
    def __init__(self, root): 
     self.root = root 
     self.root.title('Ttk Calendar') 
     frame = ttk.Frame(self.root) 
     frame.pack() 
     quit_button = ttk.Button(frame, text="Calendar", command=self.use_calendar) 
     quit_button.pack() 
     self.calendarroot = None 
    def use_calendar(self): 
     if not self.calendarroot: 
      self.calendarroot=TK.Toplevel(self.root) 
      ttkcal = Calendar(master=self.calendarroot, selection_callback=self.get_selection, firstweekday=calendar.SUNDAY) 
      ttkcal.pack(expand=1, fill='both') 
      self.calendarroot.update() 
      self.calendarroot.minsize(self.calendarroot.winfo_reqwidth(), self.calendarroot.winfo_reqheight()) 
     else: 
      self.calendarroot.deiconify() # Restore hidden calendar 

    def get_selection(self, selection): 
     print (selection) 
     self.calendarroot.withdraw() # Hide calendar - if that is what is required 

if __name__ == '__main__': 
    root = tkinter.Tk() 
    x = Test(root) 
    root.mainloop() 

我试图摧毁顶层框架,但得到一个错误,所以我用退出,deiconify,没有最好,但至少我得到了一些工作。

我意识到有点混乱的答案,但你可能会想出一个更好的解决方案。