代码之家  ›  专栏  ›  技术社区  ›  Phineas

Tkinter-无法从带有图像和文本的标签中删除边框

  •  0
  • Phineas  · 技术社区  · 2 年前

    我想裁剪与标签边界框相对应的背景,并将其设置为顶部有文本的标签背景。然而,由于某种原因,可以看到一条边界 Image of label with border

    我已经设置好了 bd=0, borderwidth=0, highlightthickness=0, relief="flat" ,但这些都不起作用。

    在上图中,我将标签的背景设置为红色。

    此外,就你的信息而言,背景图像是一个渐变色,使用纯色看起来很糟糕。

    看起来边界实际上就是背景。 即使在手动增加边界框的大小后,标签的大小似乎也会随着图像的增加而增加,并且标签周围总是有一个与背景颜色相同的边界。如果未指定背景,则边框将变为白色。 enter image description here

    如何删除此边界?

    代码如下:

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

    如果你想要渐变背景图像(background.png),这里是: Background gradient

    1 回复  |  直到 2 年前
        1
  •  0
  •   acw1668    2 年前

    这是因为 padx pady 默认情况下不为零。将它们设置为零将解决问题:

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

    后果

    enter image description here

    但是,您可以使用 .create_text() 显示透明文本,而不是使用 Label 以及从背景复制图像的区域。