tkinterのButtonの使い方について書いていきます。
この記事でやること。
- ボタンをクリックしてアプリケーションを終了させる
- ボタンをクリックしてLabelの更新をする
- ボタンをクリックできなくする。
関連リンク
The Tkinter Button Widget
7. The Button widget
minimal application
まずはメインウィンドウを用意します。
import tkinter as tk
root = tk.Tk()
"""
ここの間にボタンの処理について書いていく。
"""
root.mainloop()
上のプログラムを実行すると、このようなウィンドウが立ち上がります。

上のプログラムをベースにボタンの使い方について書いていきます。
ボタンをクリックして関数を呼び出す
ボタンをクリックしたときに関数を呼び出すようにするには引数のcommand
に関数を渡します。
(例)ボタンをクリックしたら標準出力にHelloと出力する。
def hello():
print("Hello")
button = tk.Button(root, text="Hello", command=hello)
button.pack()

ボタンをクリックしてtkinterを終了させるには引数のcommand
にメインウィンドウのインスタンスのquit
を渡す。
(例)ボタンをクリックしたらアプリケーションを終了する。
button = tk.Button(root, text="Quit", command=root.quit)
button.pack()

ボタンをクリックしたらLabelの表示を更新できるようにするには、Labelの更新処理をする関数を引数のcommand
に渡します。(※ラベルの使い方についてはこちら。)
var = tk.StringVar()
var.set("Hello")
def update_label():
import random
label_list = ["HOGE", "YES", "NO"]
var.set(random.choice(label_list))
label = tk.Label(root, textvariable=var)
label.pack()
button = tk.Button(root, text="update", command=update_label)
button.pack()
updateをクリックするとLabelの表示がランダムに変わるようにしています。

オプションについて
ボタンのオプションについていくつか紹介します。
見た目の設定①
背景の色ー>bg、文字の色ー>fg、文字の設定ー>font
枠の幅の長さー>bd、横の長さー>width、縦の長さ->height
button = tk.Button(
root, text="終了", command=root.quit,
bg="blue", fg="red", font=("Helvetica", "16", "bold"),
bd=5, width=10, height=10
)
button.pack()
アプリケーションを立ち上がげるとこのようになる。(※指定できる色についてはこちら。)

見た目の設定②
relief
でボタンの形を設定する。デフォルトではraisedになっていて、指定できるオプションにはsunken, flat, groove, ridgeがある。
button = tk.Button(root, text="終了", command=root.quit, relief="groove")
button.pack()

状態の設定
state
で状態の設定ができる。デフォルトではnormalになっており、クリックできないようにするにはconfigure()
にdisabledを渡す。
(例)ボタンAをクリックしたらボタンBをクリックできない状態にし、ボタンCをクリックしたらボタンBをクリックできる状態にするプログラム。
def activate_B():
button_B.configure(state="normal")
def disabled_B():
button_B.configure(state="disabled")
button_A = tk.Button(root, text="A", command=activate_B)
button_A.pack()
button_B = tk.Button(root, text="B", command=root.quit, state="disabled")
button_B.pack()
button_C = tk.Button(root, text="C", command=disabled_B)
button_C.pack()
