Python tkinter 设置窗口图标

最近更新于 2024-12-22 21:44

测试环境

Python 3.13.1
tkinter 8.6.15
Pillow 11.0.0

logo 为外部图片文件

通过文件的方式设置图标,在打包程序的时候注意把图片和程序一起带走,不然运行的时候找不到

ico

tkinter 可以直接使用 ico 文件,指定文件路径就行。

import tkinter

class Application(tkinter.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()

    def hello(self):
        self.label = tkinter.Label(self, text="Hello World!")
        self.label.pack()

def main():
    root = tkinter.Tk()
    root.title("你好,世界")
    root.geometry("400x20+300+200")

    # ico 文件
    logoPath = 'favicon.ico'
    root.iconbitmap(logoPath)

    app = Application(master=root)
    app.hello()
    app.mainloop()

if __name__ == '__main__':
    main()

file

任意图片文件

要支持任意图片文件就需要使用 Pillow 来打开图片

import tkinter
from PIL import ImageTk

class Application(tkinter.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()

    def hello(self):
        self.label = tkinter.Label(self, text="Hello World!")
        self.label.pack()

def main():
    root = tkinter.Tk()
    root.title("你好,世界")
    root.geometry("400x20+300+200")

    # 图片文件
    logoPath = 'favicon.png'
    logo = ImageTk.PhotoImage(file=logoPath)
    root.iconphoto(False, logo)

    app = Application(master=root)
    app.hello()
    app.mainloop()

if __name__ == '__main__':
    main()

logo 内置于代码中

logo 为外部图片文件的时候,如果缺失了图片文件可能就会导致程序执行异常,需要将图片文件和代码一起打包,将图片文件内置于代码中就不需要额外处理图片路径。
在线图片转 base64:https://iyatt.com/tools/img2base64/
将需要用作 logo 的图片转为 base64 字符串,如果图片分辨率比较大,建议先缩放一下,不然字符串非常的长。比如可以用画图,这里把图片转为 38×50 大小
file

file

import tkinter
from PIL import ImageTk, Image
import base64
from io import BytesIO
import re

class Application(tkinter.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()

    def hello(self):
        self.label = tkinter.Label(self, text="Hello World!")
        self.label.pack()

def main():
    root = tkinter.Tk()
    root.title("你好,世界")
    root.geometry("400x20+300+200")

    # 图片 base64 字符串
    logoBase64String = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACYAAAAyCAYAAAAweqkjAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsEAAA7BAbiRa+0AAAwcSURBVFhHtVl7cFTVGf/du/fubpJNyDsmIdkkRLRWLQoVCAgiVscyKDSMvOsIUguMTh2t+kfVdtpOx1bH8dFRsAaRzqhoa5WHgCD4QGeKFZAixkgIeW0SAgl5Z+/uvf199+4mAfJapR+e3HPP+e53fud7ne+sitkGC1GSnuJ0z+n/v2mQtRxgMqFlQYm/DjBPkFGHpWRwsoJ9vstH/fAHpyjPwI1FaeD358tSr+BYujPUewQwWmweG5ilJMEwNiLcOAXhjpOwzBAZ4xAO74Ua+hPBigBVPu1bV6hPvsWeTCj8Yw/Kn4GcDsmIowXpidA46uAJii6G4g1DS98Db9LfoVjlDjAlcTwaN96Hxof/iuR7V0JzU2OGCktNpRgCumCd6IuNYghyYPTTwPdo36D0s4CHf/+2CWNuXYrsJ8dBaftpFFgBAuvuRsueKrhuLsH4u+/ip4f44XNsaQMEXUwy2HLZHkTde7vR+dGH8IRT4P9zMqy2lVFghah5djniMyYgnJ2Bhj0HcMWjU+GyHgJ6Pu5X0MUi7tF0ZcHl24kTZYfhzvAjKT8Nza9uReFTRQS2UOwkxJUtBcGz7ci8YTrSJ+Xh6z98CkvbC8szuY/lojSSpU+C6vuUoCqgJRQhd24FQi1bOJPAptk8EWC9/EYa1YjfIef240ibPAvlf3kecH8Cy329Y8nv2+jvlj6V0b8BVRu+ghafjryFXwLhezl3hgzuCGMUnm3vIIdUgquF2b4F2XMuZXReS3DrMP6h96G67wdC3dx1CpvJQAySVyLLy0ZhKoWqYfKE+M7AoUzFMvgMkt9HXheDyQXVtQpVr9TBFdeLvEXNsDrWQomjBEW05YASigBz8WMKU2Qihes2Etwa5MzdxPUm4viqh+C5/iayebgwP1E8FGFGgPFblTbqa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S5bn0z5y5Rd1yRgxAwP+B+sy9IizM2AwAAAAAElFTkSuQmCC'
    # 前缀
    prefix = 'data:image/png;base64,'
    # 去除前缀
    logoData = re.sub(f'^{prefix}', '', logoBase64String)
    # 解码
    logoBytes = base64.b64decode(logoData)
    # 转为 Pillow 可读数据
    imageData = BytesIO(logoBytes)
    # Pillow 打开图像
    pillowImage = Image.open(imageData)
    # 转为 tkinter 图像
    tkinterImage = ImageTk.PhotoImage(pillowImage)
    # 设置 logo
    root.iconphoto(False, tkinterImage)

    app = Application(master=root)
    app.hello()
    app.mainloop()

if __name__ == '__main__':
    main()
Python tkinter 设置窗口图标
Scroll to top