如何在Tkin中修改日历选择

2024-10-04 11:30:40 发布

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

我有一个很棒的Tkinter代码,可以让我从日历小部件中选择日期,并在第二帧中显示日期时间文本

我真的很想让用户在第二帧有编辑功能,这样他们就可以修改选择的小时、分钟、秒。在

See the Calendar Widget Screen Shot

我试过了tkinter.入口()但我似乎无法将其与自动更新的日历联系起来。。在

参见以下代码:

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)
class SecondFrame(tkinter.Frame):

def __init__(self, *args, **kwargs):

    tkinter.Frame.__init__(self, *args, **kwargs)
    self.l = tkinter.Label( self, text="Month(MM)")
    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()   
test2()

Tags: 代码selfinitontkinterdefrootcall
1条回答
网友
1楼 · 发布于 2024-10-04 11:30:40

由于您没有指定,所以我假设您使用的是来自http://svn.python.org/projects/sandbox/trunk/ttk-gsoc/samples/ttkcalendar.py的代码,因为所有内容似乎都匹配。在

不要使用Label小部件,而是使用Entry小部件并绑定<FocusOut>事件或<KeyRelease>事件,具体取决于您是希望检查用户何时取消了元素的焦点,还是在每次更新文本之后。在

在listener函数中,从将用于设置日历日期的文本中获取datetime。在

一旦您有了datetime,请设置Calendar的选择并更新显示以显示正确的日期。在

我已经完成了您需要的所有代码:

def setdate(event):
    try:
        # parse the string into a date
        newDate = datetime.datetime.strptime(event.widget.get(), "%Y-%m-%d %H:%M:%S")
    except:
        # the string isn't a valid date, don't do anything
        return

    # change the month and year
    ttkcal._date = datetime.datetime(newDate.year, newDate.month, 1)
    # update the calendar's month and year display
    ttkcal._build_calendar()
    # get the day of the week the day falls on starting from Sunday
    weekday = (newDate.weekday() + 1) % 7

    # get the coordinates of the day in the calendar widget
    # get the x coordinate that day falls on
    x = sum(ttkcal._calendar.column(column)['width'] for column in range(weekday)) + 1 # +1 for the border
    # get the day of the week the first day of that month falls on (starting from Sunday again)
    startWeekday = (datetime.datetime(newDate.year, newDate.month, 1).weekday() + 1) % 7
    # get the row that the date would fall in
    rowNumber = int((newDate.day + startWeekday) / 7)
    # get the y coordinate that week falls on
    y = ttkcal._calendar.bbox(ttkcal._items[rowNumber])[1] + 1
    # dispatch a click to make the calendar think the user clicked on that day
    ttkcal._calendar.event_generate('<ButtonPress-1>', x=x, y=y)
    # it seems to reset the selection for some reason, so set it again
    ttkcal._date = datetime.datetime(newDate.year, newDate.month, 1)

    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    # delete the next line if you are binding to the <FocusOut> event instead of the <KeyRelease> event
    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    event.widget.focus_force()



# inside SecondFrame.__init__
self.l = tkinter.Entry(self)
self.l.pack()
self.l.bind("<KeyRelease>", setdate)

你要做的就是用那个代码替换你的__init__来代替{}。(保留tkinter.Frame.__init__(self, *args, **kwargs)当然,仅此而已)

请记住,您必须以YYYY-MM-DD HH:MM:SS的形式输入日期(例如2017-8-8 00:00:00)。您可以更改第四行的格式,其中第四行是"%Y-%m-%d %H:%M:%S"(语法here的文档)。此外,此代码需要导入datetime模块来创建日期。在

编辑: 您还需要将update_label方法更改为:

^{pr2}$

如果你希望文本在用户点击日历时也能改变

相关问题 更多 >