Tkinter嵌入ico图标#
Tkinter虽然比较简陋,但是在使用Python开发一些图形化小工具时还是比较方便的。由于原生图标比较朴素,所以一般都会选择自定义图标,但是就会遇到一个单文件可执行程序还得配一个ico文件用于显示图标,无疑比较累赘。本文介绍了如何将图标嵌入可执行文件的做法。
Jessie Wilson在stackoverflow上的问题“Embed icon in python script”给了解决方案:
1
2
3
4
5
6
7
8
|
import Tkinter as tk
icon = """
REPLACE THIS WITH YOUR BASE64 VERSION OF THE ICON
"""
root = tk.Tk()
root.iconphoto(True, tk.PhotoImage(data=icon_png))
|
其中图标要求为.png
文件,代码实现图像转换Base64
编码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
"""ico图标"""
import base64
def image_to_base64(image_path):
with open(image_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
return encoded_string
icon_png = """
base64 code
"""
if __name__ == "__main__":
print(image_to_base64("icon.png"))
|