如何更改 Tkinter 的 OptionMenu 窗口小部件的菜单背景颜色?


设想一种情况,我们需要一些用下拉列表形式显示带有某些选项的菜单。为实现此特定功能,Tkinter 提供了一个 OptionMenu 窗口小部件,其中包含添加选项和其中项目列表的功能。我们可以通过配置 OptionMenu 窗口小部件的属性(如背景色、宽度、高度、前景色等)来设置其默认行为。

示例

# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk

# Create an instance of tkinter frame
win = Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Add a Label
Label(win, text="Select a Day from the Menu", font=('Aerial 13')).pack(pady=10)

# Create a Variable to store the selection
var = StringVar()

# Create an OptionMenu Widget and add choices to it
option = OptionMenu(win, var, "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
option.config(bg="gray81", fg="white")
option['menu'].config(bg="green3")
option.pack(padx=20, pady=30)

win.mainloop()

输出

运行以上代码将显示一个 OptionMenu,其中选项为“天”。菜单具有可以用 configuration 方法更改的背景色和前景色。

更新于: 08-Jun-2021

1K+ 浏览量

开启您的职业

通过完成课程获取认证

开始学习
广告
© . All rights reserved.