python打印日历代码_带tkinter的日历(打印所选日期)
为了用tkinter创建日历,我在网上获得了以下代码:"""
Simple calendar using ttk Treeview together with calendar and datetime
classes.
"""
import calendar
import tkinter
import tkinter.font
from tkinter import ttk
def get_calendar(locale, fwday):
# instantiate proper calendar class
if locale is None:
return calendar.TextCalendar(fwday)
else:
return calendar.LocaleTextCalendar(fwday, locale)
class Calendar(ttk.Frame):
# XXX ToDo: cget and configure
datetime = calendar.datetime.datetime
timedelta = calendar.datetime.timedelta
def __init__(self, master=None, **kw):
"""
WIDGET-SPECIFIC OPTIONS
locale, firstweekday, year, month, selectbackground,
selectforeground
"""
# remove custom options from kw before initializating ttk.Frame
fwday = kw.pop('firstweekday', calendar.MONDAY)
year = kw.pop('year', self.datetime.now().year)
month = kw.pop('month', self.datetime.now().month)
locale = kw.pop('locale', None)
sel_bg = kw.pop('selectbackground', '#ecffc4')
sel_fg = kw.pop('selectforeground', '#05640e')
self._date = self.datetime(year, month, 1)
self._selection = None # no date selected
ttk.Frame.__init__(self, master, **kw)
self._cal = get_calendar(locale, fwday)
self.__setup_styles() # creates custom styles
self.__place_widgets() # pack/grid used widgets
self.__config_calendar() # adjust calendar columns and setup tags
# configure a canvas, and proper bindings, for selecting dates
self.__setup_selection(sel_bg, sel_fg)
# store items ids, used for insertion later
self._items = [self._calendar.insert('', 'end', values='')
for _ in range(6)]
# insert dates in the currently empty calendar
self._build_calendar()
# set the minimal size for the widget
#self._calendar.bind('', self.__minsize)
def __setitem__(self, item, value):
if item in ('year', 'month'):
raise AttributeError("attribute '%s' is not writeable" % item)
elif item == 'selectbackground':
self._canvas['background'] = value
elif item == 'selectforeground':
self._canvas.itemconfigure(self._canvas.text, item=value)
else:
ttk.Frame.__setitem__(self, item, value)
def __getitem__(self, item):
if item in ('year', 'month'):
return getattr(self._date, item)
elif item == 'selectbackground':
return self._canvas['background']
elif item == 'selectforeground':
return self._canvas.itemcget(self._canvas.text, 'fill')
else:
r = ttk.tclobjs_to_py({item: ttk.Frame.__getitem__(self, item)})
return r[item]
def __setup_styles(self):
# custom ttk styles
style = ttk.Style(self.master)
arrow_layout = lambda dir: (
[('Button.focus', {'children': [('Button.%sarrow' % dir, None)]})]
)
style.layout('L.TButton', arrow_layout('left'))
style.layout('R.TButton', arrow_layout('right'))
def __place_widgets(self):
# header frame and its widgets
hframe = ttk.Frame(self)
lbtn = ttk.Button(hframe, style='L.TButton', command=self._prev_month)
rbtn = ttk.Button(hframe, style='R.TButton', command=self._next_month)
self._header = ttk.Label(hframe, width=15, anchor='center')
# the calendar
#self._calendar = ttk.Treeview(show='', selectmode='none', height=7)
self._calendar = ttk.Treeview(self, show='', selectmode='none', height=7)
# pack the widgets
hframe.pack(in_=self, side='top', pady=4, anchor='center')
lbtn.grid(in_=hframe)
self._header.grid(in_=hframe, column=1, row=0, padx=12)
rbtn.grid(in_=hframe, column=2, row=0)
self._calendar.pack(in_=self, expand=1, fill='both', side='bottom')
def __config_calendar(self):
cols = self._cal.formatweekheader(3).split()
self._calendar['columns'] = cols
self._calendar.tag_configure('header', background='grey90')
self._calendar.insert('', 'end', values=cols, tag='header')
# adjust its columns width
font = tkinter.font.Font()
maxwidth = max(font.measure(col) for col in cols)
for col in cols:
self._calendar.column(col, width=maxwidth, minwidth=maxwidth,
anchor='e')
def __setup_selection(self, sel_bg, sel_fg):
self._font = tkinter.font.Font()
self._canvas = canvas = tkinter.Canvas(self._calendar,
background=sel_bg, borderwidth=0, highlightthickness=0)
canvas.text = canvas.create_text(0, 0, fill=sel_fg, anchor='w')
canvas.bind('', lambda evt: canvas.place_forget())
self._calendar.bind('', lambda evt: canvas.place_forget())
self._calendar.bind('', self._pressed)
#def __minsize(self, evt):
# width, height = self._calendar.master.geometry().split('x')
# height = height[:height.index('+')]
# self._calendar.master.minsize(width, height)
def _build_calendar(self):
year, month = self._date.year, self._date.month
# update header text (Month, YEAR)
header = self._cal.formatmonthname(year, month, 0)
self._header['text'] = header.title()
# update calendar shown dates
cal = self._cal.monthdayscalendar(year, month)
for indx, item in enumerate(self._items):
week = cal[indx] if indx < len(cal) else []
fmt_week = [('%02d' % day) if day else '' for day in week]
self._calendar.item(item, values=fmt_week)
def _show_selection(self, text, bbox):
"""Configure canvas for a new selection."""
x, y, width, height = bbox
textw = self._font.measure(text)
canvas = self._canvas
canvas.configure(width=width, height=height)
canvas.coords(canvas.text, width - textw, height / 2 - 1)
canvas.itemconfigure(canvas.text, text=text)
canvas.place(in_=self._calendar, x=x, y=y)
# Callbacks
def _pressed(self, evt):
"""Clicked somewhere in the calendar."""
x, y, widget = evt.x, evt.y, evt.widget
item = widget.identify_row(y)
column = widget.identify_column(x)
if not column or not item in self._items:
# clicked in the weekdays row or just outside the columns
return
item_values = widget.item(item)['values']
if not len(item_values): # row is empty for this month
return
text = item_values[int(column[1]) - 1]
if not text: # date is empty
return
bbox = widget.bbox(item, column)
if not bbox: # calendar not visible yet
return
# update and then show selection
text = '%02d' % text
self._selection = (text, item, column)
self._show_selection(text, bbox)
def _prev_month(self):
"""Updated calendar to show the previous month."""
self._canvas.place_forget()
self._date = self._date - self.timedelta(days=1)
self._date = self.datetime(self._date.year, self._date.month, 1)
self._build_calendar() # reconstuct calendar
def _next_month(self):
"""Update calendar to show the next month."""
self._canvas.place_forget()
year, month = self._date.year, self._date.month
self._date = self._date + self.timedelta(
days=calendar.monthrange(year, month)[1] + 1)
self._date = self.datetime(self._date.year, self._date.month, 1)
self._build_calendar() # reconstruct calendar
# Properties
@property
def selection(self):
"""Return a datetime representing the current selected date."""
if not self._selection:
return None
year, month = self._date.year, self._date.month
return self.datetime(year, month, int(self._selection[0]))
def test():
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()
if __name__ == '__main__':
test()
它工作得非常好。日历打开,我可以选择日期和一切。我有一个非常重要的问题。在这段代码中,我可以把一些简单的东西放在哪里:
^{pr2}$
并使用datetime模块格式化它?(我知道如何使用datetime以防万一)我就是不知道该从哪一部分获取用户选择的整个日期,我只是能够得到日期。我说的整个日期是指yyyy-mm-dd
任何帮助都将不胜感激。谢谢!!在
python打印日历代码_带tkinter的日历(打印所选日期)相关推荐
- python怎么输入程序代码_学习用 Thonny 写代码: 一个面向初学者的Python IDE
学习编程很难.即使当你最终怎么正确使用你的冒号和括号,但仍然有很大的可能你的程序不会如果所想的工作. 通常,这意味着你忽略了某些东西或者误解了语言结构,你需要在代码中找到你的期望与现实存在分歧的地方. ...
- python好玩的代码_一行 Python 能实现什么丧心病狂的功能?
能够把自身代码打印出来的程序,叫做Quine.下面是python的一行quine: 有人说有分号不算一行,无分号版: 其实,如果你用程序语言的名字+quine作为关键字去搜索,你能找到各种语言实现的 ...
- python新年有趣代码_搞几款由“Python”语言编写的“有趣、恶搞、好玩”的程序代码!...
下载好向圈APP可以快速联系圈友 您需要 登录 才可以下载或查看,没有帐号?立即注册 x 为提高大家对"Python"编程语言的学习兴趣,今天给大家分享几款有趣的Python程序代 ...
- lodop打印无内容_民法典新确立的打印遗嘱应如何订立能有效?| 附文书范本
前三篇文章,我们主要对自书遗嘱.代书遗嘱以及订立遗嘱的具体注意事项进行了分享.那么接下来我们林教头养老行业律师团队继续遗嘱系列普法,今天就谈谈<民法典>新确立的法定遗嘱形式-打印遗嘱,那么 ...
- java打印文档_从Java应用程序打印文档?
我正在尝试创建一个能够直接从UI打印文档的Java UI . 我能够创建和使用Javax ServiceUI,但是当从ServiceUI中选择"Print"并调用DocJob上的p ...
- iphone 日历 灰色_将iPhone假期日历更改为本地日历
iphone 日历 灰色 I usually use iPhone in the English language. However, I find the iPhone calendar app i ...
- 谷歌日历类似_如何在Google日历中查看即将到来的天气,体育比赛,电视节目等...
谷歌日历类似 Google Calendar isn't just a tool to keep track of your own events. You can subscribe to a nu ...
- python装b代码_一行python代码带你装B
一行代码,python就能让你玩出花来.今天给大家介绍几个有趣的一行代码. 1.心形字符,全中文的话可能会变形,大家可以试试中英文搭配. print('\n'.join([''.join([('Ilo ...
- python 打印自己代码_如何编写一个打印自身源代码的程序
一个程序,在没有任何外部输入的情况下,打印自身的源代码,这类程序在英文里有一个专门的称呼,叫做Quine,之所以叫这个名字,是为了纪念美国哲学家及逻辑学家Willard Van Orman Quine ...
最新文章
- centos7.x安装图形化界面
- oracle的常用sql
- 滑动窗口—满足XX条件的最长子串
- mysql1440秒未活动_phpMyAdmin登陆超时1440秒未活动请重新登录
- android多点触摸手势,安卓手势学习笔记(三) 多点触控
- struts2和struts1认识
- 在mysql中 11div4_雷林鹏分享:MySQL 运算符
- Firefox(火狐)下载时卡在最后1秒解决办法
- 特斯拉要用太阳能满足整座岛全年能源需求
- js判断手机端和pc端
- 七夕表白小代码喜欢的拿去
- CPU卡发卡总结(三)——充值和消费
- duet连win10_duetdisplay这个软件在win10上用不了?安装vs2015的时候想取消安装没有点取消...
- 点阵汉字的字模读取与显示
- 内网穿透工具NatApp使用教程
- 判断日期数组是否连续
- 邮箱如何群发邮件,公司邮件群发教程
- 怎么可以修改pr基本图形中的文字_10、Pr中基本图形安装使用,点点就可以应用高级的字幕...
- 平安科技面试问题整理
- 数据结构第二次实验-赫夫曼编码及其应用
热门文章
- 赠书5本包邮:数据思维实践、Cloud Native分布式架构原理与实践
- SQL Server 2008处理隐式数据类型转换在执行计划中的增强
- 带你掌握不同平台下,探索JDK源码所需的native方法
- 面试必问题:JS防抖与节流
- 搭建亿级时间线数据的监控系统,我有绝招!
- R语言学习笔记(五)假设检验及其R实现
- 计算机图形学E10——Bezier曲线
- LeetCode-402:移除k位数字
- Python类的成员
- max open files mysql_MySQL 重启提示超出可打开文件数限制|Buffered warning: Changed limits: max_open_files: 1024...