2

如何tabttk.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()
4

3 回答 3

3

作为一个完整的例子:

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 是受支持的格式之一。

于 2018-05-21T13:02:01.903 回答
1

@James Kent,PRMoureu 寻求帮助。这是我的错,一切正常,即使没有 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()

在此处输入图像描述

于 2018-05-22T11:41:39.353 回答
0
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()
于 2020-05-18T20:39:29.150 回答