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

标签 python python-3.x tkinter ttk

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

关于Python,如何将图像设置到ttk.notebook选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50444889/

相关文章:

python - 使用鼠标移动和缩放 tkinter Canvas

python - 如何通过单击按钮突出显示(选择)文本小部件中的文本?

python - tf.contrib.learn.LinearRegressor 的拟合函数要求切换到 tf.train.get_global_step

python - 类型错误 : argument of type 'WindowsPath' is not iterable - in open of pdf file with python

python - 使用 python 3.5 在 centos 6.5 上安装 tkinter

python 临时文件 + gzip + json 转储

python - Django 应用程序在本地运行,但我在 Heroku 上的 CSRF 验证失败

python - Dataframe 按值分组,删除重复项,但保存不相似的条目? Python

python - GeoIP 与谷歌应用引擎和 python

python - 是否可以从迭代器获取下一项的索引?