In Last time, I wrote the basic part of Tkinter in Python. This time, I will show you how to dynamically create a Tkinter Checkbutton.
A flow diagram of a simple idea.
Python
#!/usr/bin/env python
# -*- coding: utf8 -*-
import sys
import Tkinter
import tkMessageBox
root = Tkinter.Tk()
root.title(u"Software Title")
root.geometry("400x300")
#
#Global variables
#
hLabel = [] #Stores the label handle
hCheck = [] #Stores the handle of the checkbox
CheckVal = [] #Stores whether the checkbox is checked
#
#Get the check status of a checkbox
#
def check(event):
for n in range(len(CheckVal)):
if CheckVal[n].get() == True:
label = Tkinter.Label(text=u"Checked")
label.place(x=100, y=20*n + 50)
else:
label = Tkinter.Label(text=u"Not checked")
label.place(x=100, y=20*n + 50)
#Added label handle
hLabel.append(label)
#
#Dynamically create checkboxes
#
def make(ebent):
#Get the number of checkboxes to create (Entry value)
num = Entry1.get()
#Delete existing checkboxes and labels
for n in range(len(hCheck)):
hCheck[n].destroy()
hLabel[n].destroy()
#Empty the array
del CheckVal[:]
del hCheck[:]
del hLabel[:]
#Loop for the value entered in Entry1
for n in range(int(num)):
#Creating a BooleanVar
bl = Tkinter.BooleanVar()
#Determine the value of the checkbox
bl.set(False)
#Creating a checkbox
b = Tkinter.Checkbutton(text = "item" + str(n+1), variable = bl)
b.place(x=5, y=20*n + 50)
#Add the value of the checkbox to the list
CheckVal.append(bl)
#Add checkbox handle to list
hCheck.append(b)
button1 = Tkinter.Button(root, text=u'Creating a Checkbutton',width=20)
button1.bind("<Button-1>",make)
button1.place(x=90, y=5)
button2 = Tkinter.Button(root, text=u'Get check',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()
Recommended Posts