【问题标题】:Tkinter widget becoming NoneTypeTkinter 小部件变成 NoneType
【发布时间】:2013-05-25 03:03:04
【问题描述】:

这是我的代码,我试图在单击另一个框架时使框架上的边框消失,并让单击的框架获得边框。我将当前有边框的小部件存储在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"]

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

编辑:

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

【问题讨论】:

    标签: python python-2.7 tkinter


    【解决方案1】:

    答案比我想象的要简单得多;在构造函数中,调用init UI 后,我将self.selectedColor 设置为None。在我将分配转移到 initUI 之前,我最初这样做是为了充当默认值,并忘记删除该行。

    【讨论】:

      猜你喜欢
      • 2018-05-17
      • 2023-03-29
      • 1970-01-01
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 2011-03-02
      相关资源
      最近更新 更多