如何向 tkinter 标签添加左边框或右边框 [英] how to add a left or right border to a tkinter Label
问题描述
以下代码
import Tkinter as tk
root = tk.Tk()
labelA = tk.Label(root, text="hello").grid(row=0, column=0)
labelB = tk.Label(root, text="world").grid(row=1, column=1)
root.mainloop()
生产
如何向 Label
添加部分边框,以便我有
How can I add a partial border to the Label
so that I have
我看到 borderwidth=
是一个 可能的选项Label
但它处理四个边框.
I see a that borderwidth=
is a possible option of Label
but it handles the four borders.
注意:问题不在于填充单元格(这是 之前在重复评论中链接的答案)
NOTE: the question is not about padding the cell (which is the essence of the answer that was formerly linked in the duplication comment)
推荐答案
没有添加自定义边框的选项或真正简单的方法,但您可以做的是创建一个继承自 Tkinter 的 Frame
类,它创建一个包含 Label
的 Frame
.你只需要用你想要的边框颜色给 Frame
着色,并让它比 Label
稍大一点,这样它就会呈现边框的外观.
There's not an option or a real easy way to add a custom border, but what you can do is create a class that inherits from Tkinter's Frame
class, which creates a Frame
that holds a Label
. You just have to color the Frame
with the border color you want and keep it slightly bigger than the Label
so it gives the appearance of a border.
然后,您无需在需要时调用 Label
类,而是调用自定义 Frame
类的实例并指定您在类中设置的参数.举个例子:
Then, instead of calling the Label
class when you need it, you call an instance of your custom Frame
class and specify parameters that you set up in the class. Here's an example:
from Tkinter import *
class MyLabel(Frame):
'''inherit from Frame to make a label with customized border'''
def __init__(self, parent, myborderwidth=0, mybordercolor=None,
myborderplace='center', *args, **kwargs):
Frame.__init__(self, parent, bg=mybordercolor)
self.propagate(False) # prevent frame from auto-fitting to contents
self.label = Label(self, *args, **kwargs) # make the label
# pack label inside frame according to which side the border
# should be on. If it's not 'left' or 'right', center the label
# and multiply the border width by 2 to compensate
if myborderplace is 'left':
self.label.pack(side=RIGHT)
elif myborderplace is 'right':
self.label.pack(side=LEFT)
else:
self.label.pack()
myborderwidth = myborderwidth * 2
# set width and height of frame according to the req width
# and height of the label
self.config(width=self.label.winfo_reqwidth() + myborderwidth)
self.config(height=self.label.winfo_reqheight())
root=Tk()
MyLabel(root, text='Hello World', myborderwidth=4, mybordercolor='red',
myborderplace='left').pack()
root.mainloop()
如果您只需要,例如每次都在右侧有 4 个像素的红色边框,您可以将其简化一些.希望有所帮助.
You could simplify it some if you just need, for instance, a red border of 4 pixels on the right side, every time. Hope that helps.
这篇关于如何向 tkinter 标签添加左边框或右边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!