settwi
settwi

Reputation: 348

Creating a window with an unknown amount of checkboxes - Python/tkinter

I'm working on a project for my computer science class involving python and tkinter. I'm trying to make a fully-functional Monopoly game, and it's coming along well. I've finally hit one roadblock that I can't seem to overcome. I'm trying to make an interface to mortgage a user's properties, and I would like to use tkinter checkbuttons to get user input, and then mortgage all of the properties that were checked. Here's the snippet of the class I've made:

from tkinter import *

class Mortgager(Tk):
    def __init__(self,coorder):    # 'coorder' is a class that coordinates all of the
        self.coorder = coorder     # other classes together

        Tk.__init__(self,className='Mortgager')
        self.title('Mortgaging')

        self.cbuttons = []
        self.intvars = []
        for prop in coorder.active_player.properties:    # iterate through player's currently owned properties
            if not prop.mortgaged:
                self.intvars.append(IntVar(self,0))
                self.cbuttons.append(Checkbutton(self,
                                                 variable=self.intvars[-1],text=prop.get_name(),
                                                 # Most recent intvar, method returns name of property

                                                 command=self.update_cash_onscreen)
                                                 #### Not sure what to do here...
                self.cbuttons[-1].var = self.intvars[-1]
                self.cbuttons[-1].text = prop.get_name()
        i = 0
        for cbutton in self.cbuttons:    # Every three properties, new column
            cbutton.grid(column=i//3,row=i%3,sticky=W,
                         padx=5,pady=5)
            i += 1
        # Haven't finished the rest of the class...

My question is this: How can I create an arbitrary amount of checkbuttons, then tell which checkbuttons have been clicked "on the go," update some sort of Label that displays the current amount to be mortgaged, with a StringVar or something like that, and then do something with that total amount?

Thanks in advance!

Upvotes: 1

Views: 639

Answers (1)

Sainath Motlakunta
Sainath Motlakunta

Reputation: 945

I quite did not understand your code but if you want to create N checkbuttons with labels in a list "ctrls" try this

# if ctrls is a list of all lables to your checkboxes
# i is the count and j is the text of label
for i,j in enumerate(ctrls): #what ever loop you want
    var = IntVar()
    c = Checkbutton(self.master,text=j,variable=var)
    boxes.append([j.strip(),var,c])

later if you want to check which buttons are checked

for i in boxes:
    if i[1].get()==0:
        #do what ever you want 
        i[2].destroy()

Upvotes: 1

Related Questions