如何为tkinter Label添加左或右边框

6 投票
2 回答
20957 浏览
提问于 2025-04-18 06:18

以下代码

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添加一个部分边框,这样就能得到

这里输入图片描述

我注意到borderwidth=Label的一个可选项,但它是处理四个边框的。

注意:这个问题不是关于给单元格添加内边距(这正是之前重复评论中链接的答案的核心内容

2 个回答

3

我觉得没有简单的方法可以直接添加一个左边框。不过,你可以通过使用一个凹陷的标签来达到类似的效果;)

比如说:

root=Tk()
Label(root,text="hello").grid(row=1,column=1)
Label(root,text="world").grid(row=2,column=3)
Label(root,relief=SUNKEN,borderwidth=1,bg="red").grid(row=2,column=2)
Label(root).grid(row=2,column=1)
root.mainloop()

这样就能创建出你想要的那种窗口了。

4

其实没有特别简单的方法来添加自定义边框,但你可以创建一个新的类,让它继承自Tkinter的Frame类。这样,你就可以创建一个包含LabelFrame。你只需要把Frame的颜色设置成你想要的边框颜色,并且让它稍微大一点,这样就能看起来像有边框一样。

然后,当你需要使用Label的时候,不是直接调用Label类,而是调用你自定义的Frame类的一个实例,并且指定你在类里设置的参数。下面是一个例子:

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像素的红色边框,其实可以简化一下。希望这对你有帮助。

撰写回答