How do I make it so the background of a canvas in tkinter is transparent?

Viewed 156

I am trying to make it so that I have a canvas on tkinter for a turtle. I want the background of the canvas to be transparent. I use a mac. How would I do that? Here is my code:

import tkinter as tk
import string as s
import turtle as tur

root = tk.Tk()
root.title('Test')
root.geometry('1010x1010+10+10')

turtleCa = tk.Canvas(root, width=375, height=900)
turtleCa.place(x=0, y=0)
t = tur.RawTurtle(turtleCa)
t.speed(0)
t.hideturtle()

prog = 0


def hang():
    global prog
    global t
    if prog == 0:
        t.penup()
        t.goto(125, -20)
        t.pendown()
        t.goto(125, 300)
        t.goto(0, 300)
        t.goto(0, 275)
    elif prog == 1:
        t.left(180)
        t.circle(35)
    elif prog == 2:
        t.penup()
        t.goto(0, 205)
        t.pendown()
        t.goto(0, 185)
    elif prog == 3:
        t.goto(-100, 110)
    elif prog == 4:
        t.penup()
        t.goto(0, 185)
        t.pendown()
        t.goto(100, 110)
    elif prog == 5:
        t.penup()
        t.goto(0, 185)
        t.pendown()
        t.goto(0, 70)
    elif prog == 6:
        t.goto(-100, -5)
    elif prog == 7:
        t.penup()
        t.goto(0, 70)
        t.pendown()
        t.goto(100, -5)
    prog = prog + 1

for i in range(8):
    hang()

root.mainloop()
tur.mainloop()

I am trying to make the turtle Canvas (turtleCa)'s background be transparent such that the root behind it will still be visible. Thanks!

1 Answers

Instead of using root.attributes('-transparent', 1) you can use root.wm_attributes('-transparentcolor', 'red')

Here is the code

from tkinter import *
 
root = Tk()
root.geometry("400x400")
root.wm_attributes('-transparentcolor', 'red') #use a color you wont use in your project i am using red as an example
 
def transparent():
    height = 300
    width = 300

    c = Canvas(root, width = width, height = height, bg = 'red') #bg is 'red' so it is invisible
    c.pack(side="top", anchor = 'c', expand=True)

transparent()
root.mainloop()

How it looks like:

enter image description here

Related