如何在 ttk.notebook 标签中的tab
上设置图片?
以下代码无效,图片无法显示:
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()
答案 0 :(得分:2)
作为一个完整的例子:
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是支持的格式之一。
答案 1 :(得分:0)
@James Kent,PRMoureu ty求助。这是我的错,一切正常,即使没有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()
答案 2 :(得分: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()