如何设置 Tkinter 标签小部件的边框?
这里的任务是使用 Tkinter 模块起草一个Python程序来设置标签小部件的边框。 Tkinter 标签小部件是一个显示文本或图像的区域。我们可以随时更新此文本。
方法
- 导入模块
- 创建一个窗口
- 为边框设置具有所需属性的标签小部件
- 将此小部件放在创建的窗口上
Syntax: Label ( master, option, … )
Parameters:
- Master: This represents the parent window.
- Option: There are so many options for labels like bg, fg, font, bd, etc
现在要设置标签的边框,我们需要向 label 属性添加两个选项:
- borderwidth:它将代表标签周围边框的大小。默认情况下,边框宽度为 2 像素。 “bd”也可以用作borderwidth的简写。
- 浮雕:它将指定标签周围装饰边框的外观。默认情况下,它是平面。除了平面之外,还有更多可接受的值,如凸起、脊、实心等。
下面给出了设置边框并根据需要对其进行编辑的实现。
程序一:设置边框
Python3
# import tkinter
from tkinter import *
# Create Tk object
window = Tk()
# Set the window title
window.title('With_Border')
# set the window size
window.geometry('300x100')
# take one Label widget
label = Label(window, text="WELCOME TO GFG", borderwidth=1, relief="solid")
# place that label to window
label.grid(column=0, row=1, padx=100, pady=10)
window.mainloop()
Python3
# import tkinter
from tkinter import *
# Create Tk object
window = Tk()
# Set the window title
window.title('GFG')
# take Label widgets
A = Label(window, text="flat", width=10,
height=2, borderwidth=3, relief="flat")
B = Label(window, text="solid", width=10,
height=2, borderwidth=3, relief="solid")
C = Label(window, text="raised", width=10,
height=2, borderwidth=3, relief="raised")
D = Label(window, text="sunken", width=10,
height=2, borderwidth=3, relief="sunken")
E = Label(window, text="ridge", width=10,
height=2, borderwidth=3, relief="ridge")
F = Label(window, text="groove", width=10,
height=2, borderwidth=3, relief="groove")
# place that labels to window
A.grid(column=0, row=1, padx=100, pady=10)
B.grid(column=0, row=2, padx=100, pady=10)
C.grid(column=0, row=3, padx=100, pady=10)
D.grid(column=0, row=4, padx=100, pady=10)
E.grid(column=0, row=5, padx=100, pady=10)
F.grid(column=0, row=6, padx=100, pady=10)
window.mainloop()
输出:
程序2:设置边框并根据需要进行编辑。
蟒蛇3
# import tkinter
from tkinter import *
# Create Tk object
window = Tk()
# Set the window title
window.title('GFG')
# take Label widgets
A = Label(window, text="flat", width=10,
height=2, borderwidth=3, relief="flat")
B = Label(window, text="solid", width=10,
height=2, borderwidth=3, relief="solid")
C = Label(window, text="raised", width=10,
height=2, borderwidth=3, relief="raised")
D = Label(window, text="sunken", width=10,
height=2, borderwidth=3, relief="sunken")
E = Label(window, text="ridge", width=10,
height=2, borderwidth=3, relief="ridge")
F = Label(window, text="groove", width=10,
height=2, borderwidth=3, relief="groove")
# place that labels to window
A.grid(column=0, row=1, padx=100, pady=10)
B.grid(column=0, row=2, padx=100, pady=10)
C.grid(column=0, row=3, padx=100, pady=10)
D.grid(column=0, row=4, padx=100, pady=10)
E.grid(column=0, row=5, padx=100, pady=10)
F.grid(column=0, row=6, padx=100, pady=10)
window.mainloop()
输出: