LoginSignup
6
3

More than 3 years have passed since last update.

tkinterで背景が透過するFrameを作る【Python】

Last updated at Posted at 2020-03-24

tkinterで背景が透明なFrameを作る。

環境

Windows10
Python3.7

※本記事ではWin環境のみ扱います。他OSでは正常に動かない可能性が高い。

サンプルコード

from tkinter import ttk
import tkinter

root=tkinter.Tk()
root.wm_attributes("-transparentcolor", "snow")
#root.attributes("-alpha",0.5)
ttk.Style().configure("TP.TFrame", background="snow")
f=ttk.Frame(master=root,style="TP.TFrame",width="400",height="300")
f.pack()

label=ttk.Label(master=root,text="薄くならないで…",foreground="red",background="snow")
label.place(x=150,y=150)
root.mainloop()


root.wm_attributestransparentcolorに透過させたい色を指定する。今回はsnowに設定。
これより、backgroundsnowflabelの背景が透明になる。

実行結果

コメント 2020-03-24 220613.png
FrameとLabelの背景が透過して後ろの壁紙が見えています。若干Labelにsnowが見えていますが、これはどうにもなりません(気持ち悪い)

-alphaオプション

上のコードのroot.wm_attributes("-transparentcolor", "snow")
root.attributes("-alpha",0.5)のようにすると確かに-alphaの値で透明度を[0,1]で変更することができます。
しかし、
コメント 2020-03-24 220522.png
このようにrootにあるLabelなどオブジェクト全体に透過率が適用されるので注意が必要。

参考

【Python】【TkInter】透明なFrameを生成する
↑Mac環境下ではこの記事の内容で再現できるそうです(手元に環境がないので未確認)。

Linuxでも再現できないか調べはしたが、結局解決できず...
上のサンプルコードをそのまま手元のubuntu18.04.4環境下で実行すると、

Traceback (most recent call last):
  File "hoge.py", line 5, in <module>
    root.wm_attributes("-transparentcolor", "snow")
  File "/usr/lib/python3.6/tkinter/__init__.py", line 1788, in wm_attributes
    return self.tk.call(args)
_tkinter.TclError: bad attribute "-transparentcolor": must be -alpha, -topmost, -zoomed, -fullscreen, or -type

となった。

6
3
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3