如何在 Tkinter 小部件中更改边框颜色?
先决条件: Tkinter GUI , Tkinter 小部件
Tkinter 是 Python 的标准 GUI 包,它为我们提供了各种常见的 GUI 元素,例如按钮、菜单以及各种可用于构建界面的输入字段和显示区域。这些元素称为 tkinter 小部件。
在小部件的所有颜色选项中,没有直接方法可以更改小部件的边框颜色。由于小部件的边框颜色与小部件的背景颜色相关,因此无法单独设置。但是,我们确实有一些方法可以为小部件的边框着色,下面将讨论这些方法。
方法 1:使用 Frame 小部件
我们可以使用 Frame 小部件作为替代边框,而不是使用小部件的默认边框,在这里我们可以将 Frame 小部件的背景颜色设置为我们想要的任何颜色。此方法适用于每个小部件。
- 导入 tkinter 模块
- 创建一个窗口
- 使用 Frame 小部件创建一个边框变量,并将背景颜色作为其属性
- 以边框变量作为属性创建任何小部件
- 将小部件放在创建的窗口上
例子:
Python3
# import tkinter
from tkinter import *
# Create Tk object
window = Tk()
# Set the window title
window.title('GFG')
# Create a Frame for border
border_color = Frame(window, background="red")
# Label Widget inside the Frame
label = Label(border_color, text="This is a Label widget", bd=0)
# Place the widgets with border Frame
label.pack(padx=1, pady=1)
border_color.pack(padx=40, pady=40)
window.mainloop()
Python3
# import tkinter
from tkinter import *
# Create Tk object
window = Tk()
# Set the window title
window.title('GFG')
# Entry Widget
# highlightthickness for thickness of the border
entry = Entry(highlightthickness=2)
# highlightbackground and highlightcolor for the border color
entry.config(highlightbackground = "red", highlightcolor= "red")
# Place the widgets in window
entry.pack(padx=20, pady=20)
window.mainloop()
输出:
方法二:使用highlightbackground和highlightcolor
我们还可以一起使用 highlightbackground 和 highlightcolor 来为我们的小部件获取边框颜色。我们甚至可以使用 highlightthickness 属性调整边框的粗细。此方法仅适用于某些小部件,例如 Entry、Scale、Text 等
- 导入 Tkinter 模块
- 创建一个窗口
- 创建一个将 highlightthickness 设置为所需边框厚度的小部件
- 将 highlightbackground 和 highlightcolor 属性配置为所需的边框颜色
- 将小部件放在创建的窗口上
例子:
蟒蛇3
# import tkinter
from tkinter import *
# Create Tk object
window = Tk()
# Set the window title
window.title('GFG')
# Entry Widget
# highlightthickness for thickness of the border
entry = Entry(highlightthickness=2)
# highlightbackground and highlightcolor for the border color
entry.config(highlightbackground = "red", highlightcolor= "red")
# Place the widgets in window
entry.pack(padx=20, pady=20)
window.mainloop()
输出:
注意:建议使用方法 1 来设置小部件的边框颜色,因为方法 2 对某些小部件可能有效也可能无效。但是方法 1 普遍适用于任何小部件。