Tkinter小部件变为NoneType

时间:2013-05-25 03:03:05

标签: python python-2.7 tkinter

这是我的代码,我试图让一个框架上的边框在点击另一个框架时消失,并让点击的框架获得边框。我在self.selectedColor中存储当前有边框的小部件,但是当我尝试在newDrawColor中使用该变量时,该变量是NoneType。这是确切的错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1410, in __call__
    return self.func(*args)
  File "test.py", line 22, in newDrawColor
    self.selectedColor.config(highlightthickness=0)
AttributeError: 'NoneType' object has no attribute 'config'

这是代码:

def initUI(self):

    self.title("Template Maker")

    choice = Frame(self, width=20, height=20, bg="#eeeeee", bd=20, highlightthickness=2,highlightbackground="#000")
    self.selectedColor = choice
    choice.pack(side="left")
    choice.bind("<Button-1>", self.newDrawColor)

    choice = Frame(self, width=20, height=20, bg="#d6e685", bd=20, highlightbackground="#000")
    choice.pack(side="left")
    choice.bind("<Button-1>", self.newDrawColor)

    choice = Frame(self, width=20, height=20, bg="#8cc665", bd=20, highlightbackground="#000")
    choice.pack(side="left")
    choice.bind("<Button-1>", self.newDrawColor)

    choice = Frame(self, width=20, height=20, bg="#44a340", bd=20, highlightbackground="#000")
    choice.pack(side="left")
    choice.bind("<Button-1>", self.newDrawColor)

    choice = Frame(self, width=20, height=20, bg="#1e6823", bd=20, highlightbackground="#000")
    choice.pack(side="left")
    choice.bind("<Button-1>", self.newDrawColor)
    ... End important part of function

def newDrawColor(self, ev):
    ev.widget.config(highlightthickness=2)
    self.selectedColor.config(highlightthickness=0)
    self.selectedColor = ev.widget
    self.drawColor = ev.widget["background"]

关于这里有什么问题的任何想法?运行擦除变量的主循环时是否会发生某些事情?我该怎么做才能解决这个问题?

编辑:

有趣的是,使用全局变量(糟糕的做法,我知道)可行。此外,经过一些调试后,在构造应用程序类之后,但在运行mainloop之前,该属性似乎设置为NoneType。仍然会喜欢非全球解决方案。

1 个答案:

答案 0 :(得分:0)

答案比我想的要简单得多;在构造函数中,在我调用init UI之后,我将self.selectedColor设置为None。我最初将此作为默认值,然后我将作业转移到initUI,并忘记删除该行。