【Python tkinter】背景にグラデーションをつける方法:Frameの使用
2022.09.02 /

本記事ではPythonのtkinterで、Frameを利用して背景にグラデーションを付けてみたいと思います。
tkinterはPythonでGUIアプリケーションを作成することができる標準ライブラリです。基本的な使用方法については以下記事をご参照ください。

【Python】tkinterを使ったGUIアプリケーションの作成方法
tkinterでグラデーションを付ける方法としては画像を使うことが多いです。ですが既存のウィジェットを使うことでもグラデーションの背景を作成することができます。
ぜひ本記事を参考にして、グラデーションを背景に付ける方法について理解を深めてください。
背景にグラデーションをつける方法
ここではFrameウィジェットを駆使してメインウィンドウにグラデーションをつけていきます。
Frameウィジェットの使用方法については以下記事をご参照ください。

【Python tkinter】Frame(フレーム)の使い方:作成・配置・オプション一覧
方法としては5個のFrameウィジェットをメインウィンドウにplace()で配置し、それぞれのFrameウィジェットに少しずつ変更した背景色を付けます。
以下のコードを参考に作成してみてください。
import tkinter as tk
root = tk.Tk()
root.geometry("500x300")
root.title('グラデーション')
x_place=0
color_changer=200
for i in range(5):
c=str(224499+color_changer)
tk.Frame(root,width=100,height=300,bg="#"+c).place(x=x_place,y=0)
x_place=x_place+100
color_changer=color_changer+1000
root.mainloop()

上図のようにモダンなグラデーションの背景ができました。次にこのグラデーションにラベルを設置してみたいと思います。
グラデーションの背景にラベルを設置する
なにもせずplace()でラベルを設置
なにも設定を変更せずにラベルをグラデーション背景の上に設置してみます。
import tkinter as tk
root = tk.Tk()
root.geometry("500x300")
root.title('グラデーション')
x_place=0
color_changer=200
for i in range(5):
c=str(224499+color_changer)
tk.Frame(root,width=100,height=300,bg="#"+c).place(x=x_place,y=0)
x_place=x_place+100
color_changer=color_changer+1000
label = tk.Label(root, text="テキストを置いてみる")
label.place(x=200, y=130)
root.mainloop()

上図のようにラベルの背景色がそのまま残ってしまいます。
ラベルの背景色を透明化する:wm_attributes
ラベルの背景色をwm_attributesを使って透明化してみます。wm_attributesは指定した色やウィジェットを透明化することができるメソッドです。
wm_attributesを以下のようにコードに組み込み実行してみます。
import tkinter as tk
root = tk.Tk()
root.geometry("500x300")
root.title('グラデーション')
x_place=0
color_changer=200
for i in range(5):
c=str(224499+color_changer)
tk.Frame(root,width=100,height=300,bg="#"+c).place(x=x_place,y=0)
x_place=x_place+100
color_changer=color_changer+1000
label = tk.Label(root, text="テキストを置いてみる",fg="white")
root.wm_attributes('-transparentcolor', label['bg'])
label.place(x=200, y=130)
root.mainloop()

上図のようにラベルの背景色は透明になり、背景にある画面(ここでは黒)が表示されるようになります。
ラベルの背景色をグラデーションと同色にする
ラベルの背景色をグラデーションと同色にすることで違和感がないようにしてみます。ラベルのオプションについては以下記事をご参照ください。

【Python/Tkinter】Label(ラベル)の使い方:文字フォント・サイズ・色・配置の設定
import tkinter as tk
root = tk.Tk()
root.geometry("500x300")
root.title('グラデーション')
x_place=0
color_changer=200
for i in range(5):
c=str(224499+color_changer)
tk.Frame(root,width=100,height=300,bg="#"+c).place(x=x_place,y=0)
x_place=x_place+100
color_changer=color_changer+1000
label = tk.Label(root, text="テキストを置いてみる",bg="#226499",fg="white")
label.place(x=200, y=130)
root.mainloop()

上図のように違和感がほとんどなくなりました。しかしラベルの文字数が多くなると隣のグラデーションに重なり、違和感が大きくなることが予想されます。
まとめ
本記事「【Python tkinter】背景にグラデーションをつける方法:Frameの使用」はいかがでしたか。
使い方によっては利用できる方法ではありましたが、結論としてはグラデーションの画像を利用したほうが利便性はよさそうです。