【问题标题】:How to make background Transparent in TKinter by converting Label widget into Canvas widget?如何通过将 Label 小部件转换为 Canvas 小部件在 TKinter 中使背景透明?
【发布时间】:2021-03-08 11:49:53
【问题描述】:

我有一个运行良好的代码,但它没有给我透明背景,(这里是图片)经过网络研究,我找到了使用画布小部件的解决方案,我们可以使用透明背景的图片.

这是我的代码,

import tkinter as tk
from PIL import Image, ImageTk


def work(progress=1):
    if progress > 300: # define the width by yourself
        return
    tmp_images = ImageTk.PhotoImage(progress_images.resize((progress, 10))) # the image size
    lb.image = tmp_images # keep reference
    lb["image"] = tmp_images # change the image
    root.add = root.after(100, work, progress+10) # define the amplitude by yourself


root = tk.Tk()

progress_images = Image.open("path.png")
lb = tk.Label(root, bg="black")
lb.pack(side="left")
work()

root.mainloop()

但我很困惑如何将 Label 小部件更改为 Canvas ?谁能帮帮我?我还是 Tkinter 的菜鸟!!!

【问题讨论】:

    标签: python python-3.x user-interface tkinter tkinter-canvas


    【解决方案1】:

    下面是使用Canvas修改的代码:

    import tkinter as tk
    from PIL import Image, ImageTk
    
    
    def work(progress=10):
        if progress > 300: # define the width by yourself
            return
        canvas.image = ImageTk.PhotoImage(progress_images.resize((progress, 30))) # the image size
        canvas.itemconfig(pbar, image=canvas.image) # update image item
        root.add = root.after(100, work, progress+10) # define the amplitude by yourself
    
    
    root = tk.Tk()
    
    progress_images = Image.open("path.png")
    
    canvas = tk.Canvas(root, width=300, height=30, bg='black', highlightthickness=0)
    canvas.pack()
    
    pbar = canvas.create_image(0, 0, anchor='nw')  # create an image item
    
    work()
    
    root.mainloop()
    

    【讨论】:

      【解决方案2】:

      您可以使用canvas.create_text(...) 替换标签,然后使用canvas.itemconfig(...) 更新标签。我从另一个堆栈溢出问题中得到了这个 参考链接:-

      add label ..

      【讨论】:

        猜你喜欢
        • 2017-01-04
        • 1970-01-01
        • 2021-04-30
        • 1970-01-01
        • 2018-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-30
        相关资源
        最近更新 更多