在 Python 中为 Tkinter 设置背景颜色
我们可以使用 tkinter.ttk 模块自定义 tkinter 小部件。Tkinter.ttk 模块用于设置 tkinter 小部件的样式,例如设置背景色、前景色、激活按钮、向标签添加图像、调整小部件的高度和宽度等。
为了在 tkinter 小部件中添加背景色,我们可以在小部件中指定background 属性。
示例
在以下示例中,我们将创建一个按钮,该按钮将更改文本标签的背景。
#Import the tkinter library
from tkinter import *
from tkinter.ttk import *
#Create an instance of tkinter frame
win = Tk()
#Set the geometry
win.geometry("600x400")
#Add a class to style the tkinter widgets
style = ttk.Style()
style.configure('TEntry', foreground = 'red')
#Define a function to change the text color
def change_color():
text.configure(background="red")
#Create a text widget
text=Label(win,text="This is a New Text",foreground="black",
background="yellow",font=('Aerial bold',20))
text.pack(pady=20)
#Create a Button widget
Button(win, text= "Click Here", command= change_color).pack(pady=10)
win.mainloop()输出
运行以上代码将创建一个窗口,其中包含一个文本标签,背景颜色为“黄色”。

现在,单击“单击此处”按钮。它将文本标签的背景颜色更改为“红色”。

广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程语言
C++
C#
MongoDB
MySQL
Javascript
PHP