简体   繁体   中英

Python, how to set image to ttk.notebook tab

How to set image on tab in ttk.notebook tabs ?

The following code isn't working, the image doesn't appear:

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()

as a complete example:

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()

for reference i tested this to work with a gif file where the builtin PhotoImage failed, and gif is one of the supported formats.

@James Kent, PRMoureu ty for help. It's was my fault, all works properly, even without PIL.

from tkinter import *
import tkinter.ttk as ttk

root = Tk()

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

frame_main = Frame()
frame_profile = Frame()

prof_img = Photoimage(file=r'D:\my_app\img\contact.png')

notebook.add(frame_main, text='Main')
notebook.add(frame_profile, text='Profile', image=prof_img, compound=TOP)

root.mainloop()

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM