python - 尝试从嵌套字典访问 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() 函数中调用特定的检查按钮?
解决方案
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:
推荐阅读
- python - 错误的 ctypes 分配
- solr - solr 中的病毒不在“反病毒”中
- typescript - 带有嵌套函数的打字稿 ReturnType
- automata - 态射下有理语言的闭包
- python - 如何将一行中的值与另一行中的值进行比较?
- android - Firebase 迁移到 androidX 的问题
- android - NFC 正在启动应用程序,但意图是“action.MAIN”而不是“action.NDEF_DISCOVERED”
- css - 修复 MediaWiki SpecialPages 的样式布局
- javascript - 检测是否在 Javascript - iOS 中启用了 Motion & Orientation Access
- .net - 从 .Net 4.8 WPF 客户端连接到 .Net Core 2.2 Web API SignalR 集线器挂起