LoginSignup
15
22

More than 5 years have passed since last update.

PythonのTkinterでCheckbuttonを動的に作成してみる

Last updated at Posted at 2015-02-23

*はじめに

前回で,PythonのTkinterの基本的な部分は書きました.
今回は,TkinterのCheckbuttonを動的に作成する方法を載せます.

*流れ

簡単な考え方の流れ図を.
1. Tkinterの枠組みを作る
2. Checkbuttonの結果(チェックされているか否か)と,Checkbuttonのハンドルを格納するグローバルな変数を用意
3. Checkbuttonを作り,BooleanVarの内容とCheckbuttonのハンドルをグローバル変数に格納
以上です.

*コード

Python
#!/usr/bin/env python
# -*- coding: utf8 -*-
import sys
import Tkinter
import tkMessageBox


root = Tkinter.Tk()
root.title(u"Software Title")
root.geometry("400x300")


#
# グローバル変数
#
hLabel = []             #ラベルのハンドルを格納します
hCheck = []             #チェックボックスのハンドルを格納します
CheckVal = []           #チェックボックスにチェックが入っているかどうかを格納します


#
# チェックボックスのチェック状況を取得する
#
def check(event):
    for n in range(len(CheckVal)):
        if CheckVal[n].get() == True:
            label = Tkinter.Label(text=u"チェックされています")
            label.place(x=100, y=20*n + 50)
        else:
            label = Tkinter.Label(text=u"チェックされていません")
            label.place(x=100, y=20*n + 50)

        #ラベルのハンドルを追加
        hLabel.append(label)


#
# チェックボックスを動的に作成
#
def make(ebent):
    #作成するチェックボックスの個数(Entryの値)を取得
    num = Entry1.get()

    #既出のチェックボックスやラベルを削除
    for n in range(len(hCheck)):
        hCheck[n].destroy()
        hLabel[n].destroy()

    #配列を空にする
    del CheckVal[:]
    del hCheck[:]
    del hLabel[:]

    #Entry1に入力された値分ループ
    for n in range(int(num)):
        #BooleanVarの作成
        bl = Tkinter.BooleanVar()

        #チェックボックスの値を決定
        bl.set(False)

        #チェックボックスの作成
        b = Tkinter.Checkbutton(text = "項目" + str(n+1), variable = bl)
        b.place(x=5, y=20*n + 50)

        #チェックボックスの値を,リストに追加
        CheckVal.append(bl)

        #チェックボックスのハンドルをリストに追加
        hCheck.append(b)



button1 = Tkinter.Button(root, text=u'Checkbuttonの作成',width=20)
button1.bind("<Button-1>",make)
button1.place(x=90, y=5)

button2 = Tkinter.Button(root, text=u'チェックの取得',width=15)
button2.bind("<Button-1>",check)
button2.place(x=265, y=5)

Entry1 = Tkinter.Entry(root, width=10)
Entry1.place(x=5, y=5)


root.mainloop()

上記のコードの実行画面

スクリーンショット 2015-02-23 17.39.52.png

15
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
22