Tkinter Canvas 没有白色背景(使其透明)

Tkinter Canvas without white background (make it transparent)

您好,我正在尝试制作一个 canvas 以在其上创建图像,但是当我创建 canvas 时,它有这个丑陋的白色背景。

test_canvas = Canvas(main_window,100,100, bd=0, highlightthickness=0)

并且放置后,它是白色背景。

有没有什么方法可以删除那个背景并使其融入(透明)?

这里有一张图片可以看出问题(我希望白色背景消失并与其他背景融为一体)

https://imgur.com/a/FySWyyn

一个windows唯一的解决方案是使用pywin32 modul并且可以安装:

pip install pywin32

使用 pywin32 你可以改变 window exstyle and set the canvas to a layered window. A layered window 可以有一个透明的色键,就像下面的例子一样:

import tkinter as tk
import win32gui
import win32con
import win32api
        

root = tk.Tk()
root.configure(bg='yellow')
canvas = tk.Canvas(root,bg='#000000')#full black
hwnd = canvas.winfo_id()
colorkey = win32api.RGB(0,0,0) #full black in COLORREF structure
wnd_exstyle = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
new_exstyle = wnd_exstyle | win32con.WS_EX_LAYERED
win32gui.SetWindowLong(hwnd,win32con.GWL_EXSTYLE,new_exstyle)
win32gui.SetLayeredWindowAttributes(hwnd,colorkey,255,win32con.LWA_COLORKEY)
canvas.create_rectangle(50,50,100,100,fill='blue')
canvas.pack()

注意:定义透明色键后,CANVAS 中的所有颜色都将是透明的!