我尝试创建一个简单的 GUI,其中包含一个复选按钮和一个普通按钮。
该计划的目标很简单:
- 如果您选中或取消选中复选按钮,普通按钮应进入禁用模式
出了什么问题?
起初我开始收到类似“AttributeError: 'NoneType' object has no attribute 'config'”的错误 我对自己说“NoneType”对象是什么?
然后我发现我的 Button 对象在创建后就消失在某处(我在第 16 行创建它,在第 17 行尝试检索它时我得到 None)。
这是正常行为还是我做错了什么?或者是否有另一种方法来检索按钮实例并使用它?
我的主要脚本:
from tkinter import *
from import_test import GUI
root = Tk() #create root
my_gui = GUI(root) #pass it to my GUI
root.mainloop() #loop
这是带有 GUI 类的子脚本(我已经创建了 init.py 文件以及我需要的所有内容):
from tkinter import *
from tkinter import ttk
class GUI:
def __init__(self, root):
self.root = root
self.tabControl = ttk.Notebook(root)
#Tabs and tab control
self.tab = Frame(self.tabControl)
self.tabControl.add(self.tab, text = "Something")
#Buttons + check button
self.checkVal = IntVar()
self.checkButton = Checkbutton(self.tab, text = "Control", variable = self.checkVal, command = self.checkFunction).grid(row = 0, column = 0)
self.button = Button(self.tab, text = "START").grid(row = 1, column = 0)
print("This should be my button: ", self.button) #always results in "None"
self.tabControl.pack(expan = 1, fill = "both")
#if button is checked - disable the button
def checkFunction(self):
print(self.button) #always results in "None"
self.button.config(state=DISABLED) #throws AttributeError: 'NoneType' object has no attribute 'config'
最佳答案
在分配Button
之前,您调用了.grid
;与 Python 中可变对象的大多数变异方法一样,grid
修改相关对象并返回 None
。分配值,然后网格
它,你就不会遇到问题了:
self.checkButton = Checkbutton(self.tab, text = "Control", variable = self.checkVal, command = self.checkFunction)
self.checkButton.grid(row = 0, column = 0)
self.button = Button(self.tab, text = "START")
self.button.grid(row = 1, column = 0)
关于python - 对象的实例在创建后立即消失(无意中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59930567/