如何在 python 中使用 Pillow 创建日历?
Posted
技术标签:
【中文标题】如何在 python 中使用 Pillow 创建日历?【英文标题】:How do I create a calendar using Pillow in python? 【发布时间】:2022-01-22 00:22:32 【问题描述】:我正在从事一个项目,我想创建一个将在电子纸显示器上显示的日历。我设法制作了网格,但不知道如何用日历日期填充网格。网格位于显示屏的下半部分,因为我使用上半部分显示天气信息。
此代码用于创建稍后将传输到显示器的图像。
如果可能的话,我想在左侧从星期日开始的网格中显示当前月份的日期。
请指教
这是我的代码:
from PIL import Image, ImageDraw, ImageFont
import datetime
from datetime import date
from calendar import monthrange
import calendar
w, h = 480, 800
img = Image.new("RGB",(w,h), (255,255,255))
draw = ImageDraw.Draw(img)
boarder = 9
h_start= int(h/2)
h_end = int(h-boarder)
w_start = boarder
w_end = w-boarder
stepsizeV = int((w-2*boarder)/7)
stepsizeH = int((h_start-boarder)/5)
#draw.rectangle((10,h_start,w-10,h_end),outline=1,width=5,)
for x in range (boarder,w,stepsizeV):
line = ((x,h_start),(x,h_end))
draw.line(line,fill=1,width=3)
for x in range (h_start,h,stepsizeH):
line = ((w_start,x),(w_end,x))
draw.line(line,fill=50, width=3)
Curdate = date.today()
date =int(Curdate.strftime('%d'))
month = int(Curdate.strftime('%m'))
year = int(Curdate.strftime('%y'))
monthlen = calendar.monthrange(year,month)
for i in range (monthlen):
for j in range(7):
【问题讨论】:
【参考方案1】:from PIL import Image, ImageDraw, ImageFont
import datetime
from datetime import date
from calendar import monthrange
import calendar
w, h = 480, 800
img = Image.new("RGB",(w,h), (255,255,255))
draw = ImageDraw.Draw(img)
boarder = 9
h_start= int(h/2)
h_end = int(h-boarder)
w_start = boarder
w_end = w-boarder
stepsizeV = int((w-2*boarder)/7)
stepsizeH = int((h_start-boarder)/5)
#draw.rectangle((10,h_start,w-10,h_end),outline=1,width=5,)
cols=[]
rows=[]
days = 0:'Sun', 1:'Mon', 2:'Tue', 3:'Wed', 4:'Thu', 5:'Fri', 6:'Sat'
i=0
for x in range (boarder,w,stepsizeV):
line = ((x,h_start),(x,h_end))
draw.line(line,fill=1,width=3)
cols.append(x+stepsizeV/2)
if i<7:
draw.text((x+stepsizeV/2 -10, h_start-stepsizeV/2), days[i], fill=(0,0,0))
i+=1
for x in range (h_start,h,stepsizeH):
line = ((w_start,x),(w_end,x))
draw.line(line,fill=50, width=3)
rows.append(x+stepsizeH/2)
Curdate = date.today()
date =int(Curdate.strftime('%d'))
month = int(Curdate.strftime('%m'))
year = int(Curdate.strftime('%y'))
monthlen = calendar.monthrange(year,month)
k = monthlen[0] + 1
i=1
j=0
r = rows[j]
while i<= monthlen[1]:
c = cols[k]
draw.text((c,r), str(i), fill=(0,0,0))
i+=1
k = (k+1)%7
if not k:
j+=1
r = rows[j]
img.show()
【讨论】:
您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。以上是关于如何在 python 中使用 Pillow 创建日历?的主要内容,如果未能解决你的问题,请参考以下文章