我有这个精彩的Tkinter代码,可让我从日历小部件中选择日期,并在第二帧中显示日期时间文本,
我真的希望用户在第二帧中具有编辑功能,以便他们可以修改选择的小时,分钟,秒。
See the Calendar Widget Screen Shot
我尝试过tkinter.Entry(),但似乎无法将其与日历相关联以进行自动更新..
见下面的代码:
-Xss4m
答案 0 :(得分:0)
由于您没有指定,我假设您正在使用http://svn.python.org/projects/sandbox/trunk/ttk-gsoc/samples/ttkcalendar.py中的代码,因为一切似乎都匹配。
使用Label
窗口小部件并绑定Entry
事件或<FocusOut>
事件,而不是使用<KeyRelease>
窗口小部件,具体取决于您是否要检查用户何时不专心元素,或每次更新文本后。
在侦听器功能中,从用于设置日历日期的文本中获取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__
代替SecondFrame
代码。 (保持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
方法更改为:
self.l.delete(0, 'end')
self.l.insert(0, x)
如果您希望即使用户点击日历
也要更改文本