So I searched for opacity in individual tkinter widgets and I found that it is not possible with tkinter.
However, there is transparent attribute in macosx and windows which makes a color fully transparent (example here), means we can see through that area of the window completely.
Second root attribute is the -alpha which changes the opacity of the whole window (value from 0 to 1).
What I wish is to have that alpha opacity in individual widgets only (with solid background), atleast for tk canvas, so that we can make blurry/transparent effects.
(Tk canvas has the stipple method, but it is not true transparency)
PIL can also be used to make images transparent, but not widgets.
I also found a hack, which is to use the alpha and transparent attribute with the overrideredirect window + binding it with a different base window, but this hack will not work in all cases and can be problematic.
So, what I am searching is; can we use some other tricks if exists? At least for windows, maybe using win32gui or ctypes?
To be honest; this is the only important and basic thing tkinter lacks.
Tkinter canvas is actually very powerful, we can even make our own custom widgets, one example is the customtkinter library. Adding opacity in those widgets would be great.
I found the correct and easiest way to set opacity in individual tkinter widgets, using ctypes:
from ctypes import windll
import tkinter
def set_opacity(widget, value: float):
widget = widget.winfo_id()
value = int(255*value) # value from 0 to 1
wnd_exstyle = windll.user32.GetWindowLongA(widget, -20)
new_exstyle = wnd_exstyle | 0x00080000
windll.user32.SetWindowLongA(widget, -20, new_exstyle)
windll.user32.SetLayeredWindowAttributes(widget, 0, value, 2)
root = tkinter.Tk()
widget = tkinter.Button(root, bg="green", fg="white", text="TEXT")
widget.pack(padx=10, pady=10)
set_opacity(widget, 0.5)
root.mainloop()
I have also implemented this in the pywinstyles package, you can simply use the function from there.
pip install pywinstyles
Example:
pywinstyles.set_opacity(widget, value, color=None)
We can even make a specific color to be transparent within the widget. Also check this post for customtkinter: https://github.com/TomSchimansky/CustomTkinter/discussions/2214