So I'm trying to use a for loop to create multiple check buttons in Tkinter by iterating over a nested list with the text that I want to display and its variable.
The reason that I'm trying to automate this is that I may want to change the number of check buttons that I have in the future, so I thought it would be easier incorporating it in a list (that I can change later) instead of doing it manually. Here's what I've tried:
from tkinter import *
class Application(Frame):
def __init__(self, master):
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
checkbttn_info = \ # nested list
[("General Purposes", self.general_purposes),
("Young People",self.young_people),
("Education And Learning", self.education_and_learning),
("Healthcare Sector",self.healthcare_sector),
("Arts Or Heritage", self.arts_or_heritage),
("Infrastructure Support", self.infrastructure_support)
("Regenerating Areas", self.regenerating_areas)
("Community Cohesion", self.community_cohesion)]
row, col = 2, 0
for variable in checkbttn_info:
variable[1] = BooleanVar()
Checkbutton(self,
variable = variable[1],
text = variable[0]).grid(row = row, column = col, sticky = W)
if col == 2:
col = 0
row +=1
else:
col +=1
Unfortunately, I get the exception:
AttributeError: 'Application' object has no attribute 'general_purposes'
I think I understand why this is but I don't know how to fix it. The Application object doesn't have any 'general_purposes' attribute because I haven't instantiated it with the BooleanVar() object, however, no other way to do it springs to mind apart from above. I try to instantiate it within the for loop but it obviously doesn't work...
Is there a way to fix the exception or a better way to do it overall? Thanks in advance for any suggestions!