Tkinterを利用してボタンを実装してみます。
カウントボタンをクリックすると、ラベルで表示されている0(ゼロ)の数値が増えていきます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
from tkinter import * root = Tk() root.title("ボタン") root.geometry("200x150") counter = 0 def count(): global counter counter += 1 count_label["text"] = counter btn = Button(root, text="カウント", command=count) btn.place(x= 50, y=50) count_label = Label(root, text="0") count_label.place(x = 50, y = 80) root.mainloop() |
9~12行目
関数をcountという名前で定義しています。この関数を呼び出すごとにcounter変数に1を足し、ラベル(18・19行目)に表示させています。
14行目
commandオプションに、ボタンをクリックした際に呼び出す関数(名)を設定しています。