首页 > 解决方案 > 尝试从嵌套字典访问 tkinter 检查按钮时出现 NoneType 错误

问题描述

我使用 for 循环checkbuttons在应用程序中创建了一组 (6)。tkinter到目前为止,我刚刚创建并布置了它们,但什么也没做。我希望他们做的是告诉另一个函数如何工作,具体取决于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()功能,我想要的是检查按钮来修改该功能的结果,所以我尝试的是

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错误地调用了嵌套,但我尝试移动我的代码并尝试不同的点点滴滴,但我一直收到同样的错误。

更新

根据以下雨果的回答,我将 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)`

variable我将如何在我的 roll() 函数中调用特定的检查按钮?

标签: pythontkinter

解决方案


self.att_buttons["Str"]["checkbutton"]return None,这就是 Python 抱怨你试图调用get()它的原因。

你写了:

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

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


另外,我认为这不是获取复选框状态的正确方法——请参阅Getting Tkinter Check Box State

回应您的编辑:

您添加了一个 BooleanVar 但您需要保留对它的引用,因为这就是您访问实际值的方式:

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

这是您如何执行此操作的示例,您只需要保留对 BooleanVar 的引用即可稍后访问它们:

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

推荐阅读