You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ttk.Notebook选项卡上设置图片?代码不生效求助

解决ttk.Notebook选项卡图片不显示的问题

这个问题我熟!你的代码里图片无法显示的核心原因是tkinter的PhotoImage对象存在引用陷阱:如果没有对它保持一个持久的引用,Python的垃圾回收机制会自动销毁这个对象,导致图片加载失败。你在notebook.add()方法里直接创建tk.PhotoImage的方式,会让这个图片对象在方法执行完成后立刻失去引用,被回收掉,所以选项卡上看不到图片。

下面给你两种靠谱的解决办法:

方法一:把图片对象绑定到Notebook实例上

先创建PhotoImage并保存为notebook的属性,确保它一直被引用:

import tkinter as tk
from tkinter import ttk

class Tab(tk.Frame):
    def __init__(self, master, *args, **kwargs):
        super().__init__(master, *args, **kwargs)
        self.label = tk.Label(self, text='Blablablee')
        self.label.pack()

root = tk.Tk()
notebook = ttk.Notebook(root)
notebook.pack()

# 先创建图片对象并保存到notebook的属性中,维持引用
notebook.tab1_icon = tk.PhotoImage(file='icon.png')
# 添加选项卡时使用这个已保存的图片对象
notebook.add(Tab(notebook), text='Tab1', image=notebook.tab1_icon, compound='left')

root.mainloop()

方法二:把图片对象绑定到自定义Tab实例上

如果每个选项卡的图标不同,把图片和Tab对象绑定在一起更合理:

import tkinter as tk
from tkinter import ttk

class Tab(tk.Frame):
    def __init__(self, master, icon_path=None, *args, **kwargs):
        super().__init__(master, *args, **kwargs)
        # 如果传入图标路径,就创建图片对象并保存到实例属性
        if icon_path:
            self.icon = tk.PhotoImage(file=icon_path)
        self.label = tk.Label(self, text='Blablablee')
        self.label.pack()

root = tk.Tk()
notebook = ttk.Notebook(root)
notebook.pack()

# 创建Tab时传入图标路径,再添加到notebook
tab1 = Tab(notebook, icon_path='icon.png')
notebook.add(tab1, text='Tab1', image=tab1.icon, compound='left')

root.mainloop()

额外提示:处理非PNG格式的图片

如果你的图片是JPG、BMP等tkinter原生PhotoImage不支持的格式,需要借助PIL库来加载:

import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk

class Tab(tk.Frame):
    def __init__(self, master, *args, **kwargs):
        super().__init__(master, *args, **kwargs)
        self.label = tk.Label(self, text='Blablablee')
        self.label.pack()

root = tk.Tk()
notebook = ttk.Notebook(root)
notebook.pack()

# 使用PIL加载非PNG图片,同样要保存引用
notebook.tab1_icon = ImageTk.PhotoImage(Image.open('icon.jpg'))
notebook.add(Tab(notebook), text='Tab1', image=notebook.tab1_icon, compound='left')

root.mainloop()

内容的提问来源于stack exchange,提问作者Acamori

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:20:31