Tkinter ボタンの状態を変更する方法

Tkinter ボタンは二つの状態があります。
NORMAL
- ユーザーはこのボタンをクリックできますDISABLED
-ユーザーはこのボタンはクリックできません
try:
import Tkinter as tk
except:
import tkinter as tk
app = tk.Tk()
app.geometry("300x100")
button1 = tk.Button(app, text="Button 1",
state=tk.DISABLED)
button2 = tk.Button(app, text="EN/DISABLE Button 1")
button1.pack(side=tk.LEFT)
button2.pack(side=tk.RIGHT)
app.mainloop()
左のボタンは無効(淡色表示)で、右のボタンは正常です。
状態は辞書(dictionary
)のような方法でも構成のような方法でも修正できます。
try:
import Tkinter as tk
except:
import tkinter as tk
def switchButtonState():
if (button1['state'] == tk.NORMAL):
button1['state'] = tk.DISABLED
else:
button1['state'] = tk.NORMAL
app = tk.Tk()
app.geometry("300x100")
button1 = tk.Button(app, text="Python Button 1",
state=tk.DISABLED)
button2 = tk.Button(app, text="EN/DISABLE Button 1",
command = switchButtonState)
button1.pack(side=tk.LEFT)
button2.pack(side=tk.RIGHT)
app.mainloop()
button 2
をクリックすることにより、switButotonState
関数を呼び出して button 1
状態を DISABLED
から NORMAL
に切り替えたり、逆に切り替えたりします。
state
は Tkinter ボタンウィジェットのオプションです。すべてのウィジェットのオプションは Button
辞書のキーです。
def switchButtonState():
if (button1['state'] == tk.NORMAL):
button1['state'] = tk.DISABLED
else:
button1['state'] = tk.NORMAL
Button
辞書の state
の値を更新することにより、ボタンの state
状態が更新されました。
state
は、Button
オブジェクトを変更する config
方法で変更することもできます。したがって、switch ButonState()
関数も以下のように実現できます。
def switchButtonState():
if (button1['state'] == tk.NORMAL):
button1.config(state=tk.DISABLED)
else:
button1.config(state=tk.NORMAL)
さらに、文字列 normal
と disabled
を使って、状態を切り替えることもできます。tk.NORMAL
と tk.DISABLED
を使わなくてもいいです。
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn