pythontkinterpython-imaging-library

Tkinter - Cant remove border from Label with image and text


I want to crop the background corresponding to bounding box of the label and set that as the label background with the text on top. However for some reason, there is a border that can be seen Image of label with border

I already set bd=0, borderwidth=0, highlightthickness=0, relief="flat", and none of this worked.

In the image above, I set the background of the label to red.

Also, for your infomation, the background image is a gradient and using a plain colour looks very bad on it.

It appears that the border is actually the background. Even after increasing the size of the bounding box manually, the label's size seems to increase along with the image, and there is always a border around it with the colour of the background. If the background is not specified, the border becomes white. enter image description here

How can I remove this border?

The code is below:

import tkinter as tk
from PIL import Image, ImageTk

root = tk.Tk()
root.geometry("500x500")

current_background = Image.open("assets/background.png")
canvas = tk.Canvas(root, borderwidth=0, highlightthickness=0)
canvas.pack(side="top", fill=tk.BOTH, expand=True)
background = ImageTk.PhotoImage(current_background)
canvas.create_image(0, 0, image=background, anchor="nw", tags="background")

logo_title = tk.Label(canvas, text="Sign In", font=("Calibri", 15), bd=0, borderwidth=0, highlightthickness=0, relief="flat", bg="red")
logo_title.pack(anchor="nw", pady=(10, 0), padx=(10, 0), side=tk.LEFT)

root.update()
root.update_idletasks()
x1, y1 = logo_title.winfo_x(), logo_title.winfo_y()
x2, y2 = x1 + logo_title.winfo_width(), y1 + logo_title.winfo_height()
background_at_bbox = current_background.crop((x1, y1, x2, y2))
label_background = ImageTk.PhotoImage(background_at_bbox)
logo_title.config(image=label_background, compound="center")

root.mainloop()

If you want the gradient background image (background.png), here it is: Background gradient


Solution

  • It is because the padx and pady are not zero by default. Set them to zero will fix the issue:

    logo_title = tk.Label(canvas, text="Sign In", font=("Calibri", 15), bd=0, borderwidth=0,
                          padx=0, pady=0, highlightthickness=0, relief="flat", bg="red")
    

    Result:

    enter image description here

    However, you can use .create_text() to show transparent text instead of using Label and copying region of image from the background.