试图从嵌套dict访问tkinter checkbuttons时,非类型错误



我使用循环在tkinter应用中创建了checkbuttons的集合(6(。到目前为止,我刚刚创建并布置了它们,但什么也没做。我希望他们要做的是告诉另一个功能如何根据单击哪个checkbutton进行工作,但是当我尝试访问checkbuttons时,我会收到问题底部发布的错误。

我尝试将所有按钮作为单个编码进行制作,但显然这是很多重复的代码,所以我用for循环制作了它们,并将它们存储在嵌套的dict中,例如:

for i in self.atts:
    self.att_buttons[i] = {}
    self.att_buttons[i]["checkbutton"] = tk.Checkbutton(
        self.check_frame, text=i, font=("Courier", 15),
        onvalue = 1, offvalue = 0,
    ).pack(side=tk.LEFT)

我不确定这是对的,但我是新手,我尽力而为。

我有一个 roll()函数,我想要的是checkbuttons修改该功能的结果,因此我尝试的是

def roll(self):
    """Roll dice, add modifer and print a formatted result to the UI"""
    value = random.randint(1, 6)
    if self.att_buttons["Str"]["checkbutton"].get() == 1:
        result = self.character.attributes["Strength"]["checkbutton].get()
        self.label_var.set(f"result: {value} + {result} ")
File "main_page.py", line 149, in roll
    if self.att_buttons["Str"]["checkbutton"].get() == 1: 
AttributeError: 'NoneType' object has no attribute 'get'

现在,我认为这是因为我错误地调用了嵌套的dict,但是我尝试移动代码并尝试不同的位和零件,并且我会遇到相同的错误。

Update

根据下面的雨果的回答,我已经编辑了for循环为

for i in self.atts:
    self.att_buttons[i] = {}
    self.att_buttons[i]["checkbutton"] = tk.Checkbutton(
        self.check_frame, text=i, font=("Courier", 15),
        variable = tk.BooleanVar()#this is the change 
    )
    self.att_buttons[i]["checkbutton"].pack(side=tk.LEFT)`

我如何在roll((函数中的特定checkbuttons调用variable

self.att_buttons["Str"]["checkbutton"]返回None,这就是为什么Python抱怨您尝试在其上调用get()

您写道:

for i in self.atts:
    self.att_buttons[i]["checkbutton"] = ...`

检查这实际上发生在具有错误的行之前,并检查self.atts是否包含"Str"


另外,我认为这不是获得复选框状态的正确方法 - 请参阅获取TKINTER复选框状态。

响应您的编辑:

您添加了一个布鲁尔瓦尔,但您需要对其进行参考,因为这就是您将访问实际值的方式:

# Make a dict associating each att with a new BooleanVar
self.att_values = {att: tk.BooleanVar() for att in self.atts}
for i in self.atts:
    self.att_buttons[i] = {}
    self.att_buttons[i]["checkbutton"] = tk.Checkbutton(
        self.check_frame, text=i, font=("Courier", 15),
        variable = self.att_values[i] 
    )
    self.att_buttons[i]["checkbutton"].pack(side=tk.LEFT)`

这是您如何做的一个示例

if self.att_values["Str"].get() == 1:

相关内容

最新更新