我可以将图像/标签放入 Tkinter 的选项框中吗?

问题描述

我不知道是否有可能实现这样的目标:

[?日出↕] 一世 (最好是调整大小为标签的图像)

解决方法

OptionMenu 不直接支持它,但 OptionMenu 只是一个 Menubutton 和一个 Menu。您可以在创建小部件后遍历菜单并添加图像。

这是一个简单的例子:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

image1 = tk.PhotoImage(width=16); image1.put('red',to=(0,15,15))
image2 = tk.PhotoImage(width=16); image2.put('green',15))
image3 = tk.PhotoImage(width=16); image3.put('blue',15))
images = {"red": image1,"green": image2,"blue": image3}

colorvar = tk.StringVar(value="red")
om = tk.OptionMenu(root,colorvar,"red","green","blue")
menu = om.nametowidget(om.menuname)
for label,image in images.items():
    print(f"configuring {label}")
    menu.entryconfigure(label,image=images[label],compound="left")

om.pack(padx=20,pady=20)

root.mainloop()

screenshot