Tkinterのオン/オフトグルボタンスイッチ
Tkinterは、アプリケーションに必要なさまざまな種類のウィジェットを追加するための機能を提供します。これらのウィジェットには、ボタンウィジェット、エントリウィジェット、テキストボックス、スライダーなどがあります。この記事では、ボタンをオンまたはオフにできるアプリケーションを作成する方法を説明します。
この例では、これら2つのボタンをデモに使用します
-
スイッチをオンにする
-
スイッチを切る
例
# Import tkinter in the notebook
from tkinter import *
# Create an instance of window of frame
win =Tk()
# set Title
win.title('On/Off Demonstration')
# Set the Geometry
win.geometry("600x400")
win.resizable(0,0)
#Create a variable to turn on the button initially
is_on = True
# Create Label to display the message
label = Label(win,text = "Night Mode is On",bg= "white",fg ="black",font =("Poppins bold", 22))
label.pack(pady = 20)
# Define our switch function
def button_mode():
global is_on
#Determine it is on or off
if is_on:
on_.config(image=off)
label.config(text ="Day Mode is On",bg ="white", fg= "black")
is_on = False
else:
on_.config(image = on)
label.config(text ="Night Mode is On", fg="black")
is_on = True
# Define Our Images
on = PhotoImage(file ="on.png")
off = PhotoImage(file ="off.png")
# Create A Button
on_= Button(win,image =on,bd =0,command = button_mode)
on_.pack(pady = 50)
#Keep Running the window
win.mainloop() 出力
上記のコードを実行すると、オン/オフモードで動作するボタンが作成されます。
ボタンをクリックすると、次のように変化します-
-
Pythontkinterボタンにスタイルを追加
Tkinterは、Pythonに基づくGUIプログラムの作成を強力にサポートしています。フォント、サイズ、色などに基づいて、Tkinterキャンバス上のボタンのスタイルを設定するさまざまな方法を提供します。この記事では、キャンバス上の特定のボタンまたは一般的なすべてのボタンにスタイルを適用する方法を説明します。 特定のボタンに適用する キャンバスに2つのボタンがあり、最初のボタンにのみスタイルを適用したい場合を考えてみましょう。構成の一部として、フォントと前景色とともにW.TButtonを使用します。 例 from tkinter import * from tkinter.ttk impo
-
PythonTkinterボタンに画像を追加
Pythonプログラミング用のGUIライブラリであるTkinterには、GUIボタンに画像を追加する機能があります。これは、ユーザーがGUIのテキストではなく、GUIの記号を覚えておくのに役立ちます。以下のTkinterプログラムでは、GUIボタンに画像を追加する方法を示しています。 imageKTモジュールのphotoimageメソッドが使用されます。画像ファイルへのローカルパスについて説明します。 例 from tkinter import * from PIL import ImageTk ,Image base = Tk() base.title('Start Button&