python - 对象的实例在创建后立即消失(无意中)

标签 python python-3.x tkinter

我尝试创建一个简单的 GUI,其中包含一个复选按钮和一个普通按钮。

该计划的目标很简单:

  • 如果您选中或取消选中复选按钮,普通按钮应进入禁用模式

出了什么问题?

  • 起初我开始收到类似“AttributeError: 'NoneType' object has no attribute 'config'”的错误 我对自己说“NoneType”对象是什么?

  • 然后我发现我的 Button 对象在创建后就消失在某处(我在第 16 行创建它,在第 17 行尝试检索它时我得到 None)。

  • 这是正常行为还是我做错了什么?或者是否有另一种方法来检索按钮实例并使用它?

奇怪的是该对象仍然显示在屏幕上: enter image description here

我的主要脚本:

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/

相关文章:

Python:制作全局单元测试功能

python - 我如何优化这个 Asyncio 代码片段以在突发期间每秒发出更多请求?

python - Tkinter打开文件窗口,文件扩展名区分大小写

python - 为什么 Photoimage put() 很慢?

python - dict 格式键错误 '0'

python - 使用 pandas 将 Flask 应用程序部署到 Elastic Beanstalk

python - Django 在类中排序代码

python - 在 Python 3 中使用 partial 在元类中创建实例方法

python - Julia 中的 "colptr"及其在 Python 中的对应项是什么?

python - 如何在 tkinter 中查看 TreeView 的部分区域和水平滚动?