Skip to main content
 首页 » 编程设计

Python,如何将图像设置为 ttk.notebook 选项卡

2024年09月07日6JeffreyZhao

如何在 ttk.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.add(Tab(notebook),  
             text='Tab1',  
             image=tk.PhotoImage(file='icon.png'),  
             compound='left') 
root.mainloop() 

请您参考如下方法:

作为一个完整的例子:

import tkinter as tk # global imports are bad 
from tkinter import ttk 
from PIL import Image, ImageTk 
 
root = tk.Tk() 
nb = ttk.Notebook(root) 
nb.pack(fill='both', expand=True) 
 
f = tk.Frame(nb) 
tk.Label(f, text="in frame").pack() 
 
# must keep a global reference to these two 
im = Image.open('path/to/image') 
ph = ImageTk.PhotoImage(im) 
 
# note use of the PhotoImage rather than the Image 
nb.add(f, text="profile", image=ph, compound=tk.TOP) # use the tk constants 
 
root.mainloop() 

作为引用,我测试了它可以使用内置 PhotoImage 失败的 gif 文件,而 gif 是受支持的格式之一。