创建一个包含未知数量复选框的窗口 - Python / tkinter

时间:2014-12-07 04:49:50

标签: python tkinter

我正在为涉及python和tkinter的计算机科学课程开发一个项目。我正在努力打造一款功能齐全的大富翁游戏,它的表现也很好。我终于找到了一个我似乎无法克服的障碍。我正在尝试建立一个抵销用户属性的界面,我想使用tkinter checkbuttons来获取用户输入,然后抵押所有已检查的属性。这是我所做的课程的片段:

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...

我的问题是:如何创建任意数量的支票按钮,然后告诉我们“随时随地”点击了哪些支票按钮,更新某种显示当前抵押金额的Label,一个StringVar或类似的东西,然后用这个总额做一些事情?

提前致谢!

1 个答案:

答案 0 :(得分:1)

我完全不明白你的代码,但如果你想在列表中创建带有标签的N个支票按钮“ctrls”试试这个

# 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])

以后如果要检查选中的按钮

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