使用未知数量的复选框创建窗口Python/tkin

2024-09-29 18:45:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为我的计算机科学课做一个涉及python和tkinter的项目。我正在尝试制作一款功能齐全的垄断游戏,而且进展顺利。我终于遇到了一个似乎无法克服的障碍。我正在尝试创建一个接口来抵押用户的属性,我想使用tkinter checkbutton获取用户输入,然后抵押所有已检查的属性。以下是我所学课程的片段:

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

我的问题是:如何创建一个任意数量的checkbutton,然后告诉哪些checkbutton已经被点击了,用一个StringVar更新某种显示当前要抵押的金额的Label,然后用这个总数做些什么?在

提前谢谢!在


Tags: ofthe用户nameself属性tkinterproperties
1条回答
网友
1楼 · 发布于 2024-09-29 18:45:58

我完全不明白你的代码,但是如果你想创建一个列表“ctrls”中的N个checkbutton,试试这个

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

如果要检查选中了哪些按钮,请稍候

^{pr2}$

相关问题 更多 >

    热门问题