There may* be platform-dependent options, like this.
(* In Lubuntu 18.04 & python 3.6.9, they don't seem to work,
so I can't test them.)
One cross-platform(?) option, is to use Canvas.
Then draw images* on the canvas, instead of using widgets.
(*whose alpha channel, determines their transparent pixels)
This will draw foreground/background elements correctly,
& Canvas has enough functionality to control elements on it
(but will need work, if you want to emulate full widgets).
Canvas offers various create_xyz
methods, where xyz:
arc
, line
, rectangle
, bitmap
, oval
, text
, image
, polygon
,
window
(<- read 'widget')*.
These return an id, that represents the item in the canvas.
Items can also be associated in groups, represented by tags.
* When using widgets in Canvas, there are some restrictions:
https://tcl.tk/man/tcl8.6/TkCmd/canvas.htm#M163
"Note: due to restrictions in the ways that windows are managed,
it is not possible to draw other graphical items
(such as lines and images) on top of window items.
A window item always obscures any graphics that overlap it,
regardless of their order in the display list."
Items in a canvas, can be configured & have event-handlers:
itemconfig
/ itemcget
tag_bind
/ tag_unbind
These can use either an individual item-id, or* a group-tag.
(* despite the 'tag_' in the name, they also take item-ids)
Many other Canvas methods work with item-ids or group-tags
(e.g. move
, delete
,).
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=300, height=300)
canvas.pack()
# Note:
# If the images overlap exactly (same position & extent),
# the bottom one will never? get any events.
# Maybe events can be propagated, not sure right now.
fgImg = tk.PhotoImage(master=root, file='media/fg.png')
fgImgId = canvas.create_image(
80, 80, anchor=tk.NW, image=fgImg
)
canvas.tag_bind(
fgImgId,
'<ButtonRelease-1>',
lambda e: canvas.tag_raise(fgImgId)
)
bgImg = tk.PhotoImage(master=root, file='media/bg.png')
bgImgId = canvas.create_image(
0, 0, anchor=tk.NW, image=bgImg
)
canvas.tag_bind(
bgImgId,
'<ButtonRelease-1>',
lambda e: canvas.tag_raise(bgImgId)
)
root.mainloop()
There are more StackOverflow questions about this, e.g.:
transparent-background-in-a-tkinter-window
python-tkinter-label-background-transparent
configure-tkinter-ttk-widgets-with-transparent-backgrounds-ttk-frame-background
and more.
You might also want to look into other gui toolkits.
(e.g. wxpython*, pyqt, )
(*Here it says, that it has a SetTransparent
command.)