赞
踩
在后台回复【阅读书籍】
即可获取python相关电子书~
Hi,我是山月。
明天就是元旦啦,提前祝大家元旦快乐呀~
据说,四叶草的四片叶子代表了:名誉、财富、爱情及健康。
因此山月想用四叶草给大家写份祝福,希望把幸运带给你们。
完整代码和用到的文件都已经打包好啦,在后台回复【元旦祝福】自取哦~
下面我们具体的来看看怎么实现的吧。
1、画一片四叶草
我们这部分用到的是tkinter,关于tkinter的基础知识,大家可以看看:初识Tkinter:一些必须掌握的基础知识。
现在我们来看看吧:
- import tkinter
-
- #创建tkinter窗口
- root = tkinter.Tk()
- root.geometry("640x400")
- root.title("元旦快乐")
-
- img = tkinter.PhotoImage(file='四叶草.png') # 导入图片
- tkinter.Label(root,image=img).place(relx=0.5, rely=0.5) #通过label在指定位置插入图片
-
- root.mainloop()
结果是:
一片小小的四叶草就显示出来啦,这步还是很简单的吧。
下一步我们就需要通过点阵字,得出每个汉字的点阵位置,并在每个位置上放上一片四叶草。
2、获取汉字的汉字点阵图
关于点阵图的知识参考自:https://blog.twofei.com/embedded/hzk.html。
下面我们来看看具体的实现代码,比如实现【元】字:
- import binascii
- import tkinter
-
- #创建tkinter窗口
- root = tkinter.Tk()
- root.geometry("640x400")
- root.title("元旦快乐")
-
- # 导入图片
- img = tkinter.PhotoImage(file='四叶草.png')
-
- # 要显示的汉字
- text = ("元")
-
- #初始化点阵
- point_list = [] * 16
- for i in range(16):
- point_list.append([] * 16)
-
- #获取中文的编码
- encode_gb = text.encode('gb2312')
- hex_str = binascii.b2a_hex(encode_gb)
- result = str(hex_str, encoding='utf-8')
-
- #计算在汉字库中的位置
- area_code = eval('0x' + result[:2]) - 0xA0
- bit_code = eval('0x' + result[2:]) - 0xA0
- offset_position = (94 * (area_code-1) + (bit_code-1)) * 32
-
- font_point = None
-
- #读取HZK16汉字库文件中数据
- with open("HZK16", "rb") as font_library:
- font_library.seek(offset_position)
- font_point = font_library.read(32)
-
- #给16*16的点阵赋值
- KEYS = [0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01]
- for k in range(len(font_point) // 2):
- row_list = point_list[k]
- for j in range(2):
- for i in range(8):
- asc = font_point[k * 2 + j]
- value = asc & KEYS[i]
- row_list.append(value)
-
- #获取列表里不为0的数值索引
- num_list = []
- for row in point_list:
- index_point = [i for i, j in enumerate(row) if j != 0]
- num_list.append(index_point)
-
- #根据索引位置放上图片
- for i in range(16):
- for j in num_list[i] :
- x = 0.05+0.01*j
- y = 0.08+i*0.02
- tkinter.Label(root,image=img).place(relx=x,rely=y)
-
- root.mainloop()

效果:
最后要做的就是运用循环,读取每一个汉字,然后注意留一下每个汉字之间的间隔,就万事大吉啦。
这里山月就不演示了,大家可以自己去试着完成一下。
完整的代码、用到的四叶草图片和HZK16汉字库山月都给大家整理好了,在公众号后台回复【元旦祝福】既可以获取。
已经到底啦~(≧▽≦*)/~
往 期 推 荐
您的“点赞”、“在看”和 “分享”是我们产出的动力。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。