how to add a left or right border to a tkinter Label

python, tkinter

Solution

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.

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()

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.

Problem

The follwing code ``` 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() ``` produces How can I add a partial border to the `Label` so that I have 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)

Original source

Related problems