Aleksas
Aleksas

Reputation: 66

Tkinter Canvas without white background (make it transparent)

Hi I'm trying to make a canvas to create images onto it, but when I create the canvas, it has this ugly white background.

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

And after placing it, it has a white background.

Is there anyway to remove that background and make it blend in (be transparent)?

Here's an image to see the problem (I want that white background to disappear and blend in with the rest of the background)

https://i.sstatic.net/15fib.jpg

Upvotes: 1

Views: 1879

Answers (1)

Thingamabobs
Thingamabobs

Reputation: 8037

A windows only solution is to use the pywin32 modul and can be installed with:

pip install pywin32

With pywin32 you can alter the window exstyle and set the canvas to a layered window. A layered window can have a transparent colorkey and is done like in the exampel below:

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

NOTE: AFTER DEFINING A TRANSPARENT COLORKEY EVERYTHING IN THAT CANVAS WITH THAT COLOR WILL BE TRANSPARENT!

enter image description here

Upvotes: 0

Related Questions