2013-07-08 73 views
1

我正在Python 2.7中编写一个Tkinter应用程序,但我遇到了一些我以前没有遇到的麻烦。从我所知道的情况来看,Tkinter模块看起来像是在我的课程中为__init__函数导入的,但不适用于其他函数。下面是我的本钱简化版本:Tkinter导入时出错

from Tkinter import * 

class App: 
    def __init__(self): 
     self.master = Tk() 
     self.window = Frame(self.master) 
     self.window.grid() 

     self.BuildFrames() 
     self.master.mainloop() 

    def BuildFrames(self): 
     frames = [] 
     frames.append(Frame(self.window,borderwidth=2,padx=10,pady=10)) 
     # more code follows... 

     for Frame in frames: 
      Frame.grid() 


App() 

当我运行它,我得到以下错误:

Traceback (most recent call last): 
    File "myApp.py", line 131, in <module> 
    App() 
    File "myApp.py", line 12, in __init__ 
    self.BuildFrames() 
    File "myApp.py", line 26, in BuildFrames 
    frame1 = Frame(self.window,borderwidth=2,padx=10,pady=10) 
UnboundLocalError: local variable 'Frame' referenced before assignment 

从我所知道的,Frame功能不被认可作为BuildFrames()函数中的Tkinter方法。如何在__init__中识别,但不在BuildFrames内?

我可以通过改变进口来解决这个问题:

import Tkinter as Tk 

,然后在所有的Tkinter方法前添加Tk.,但宁愿避免它(我不应该这样做无论如何!)

我一定错过了一些关于导入方式的大作,但是我可以发誓,这种相同类型的代码已经为我工作过。有人能帮我解决这个问题吗?

回答

1

也许某处在您的代码中,存在Frame = ...。将该变量重命名为Frame以外的其他变量。

你正在做类似下面的代码的东西:

>>> def f(): 
...  a + 1 
...  a = 0 
... 
>>> f() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 2, in f 
UnboundLocalError: local variable 'a' referenced before assignment 

Why am I getting an UnboundLocalError when the variable has a value?

编辑

更改BuildFrames如下:

def BuildFrames(self): 
    frames = [] 
    frames.append(Frame(self.window,borderwidth=2,padx=10,pady=10)) 
    # more code follows... 

    for frame in frames: 
     frame.grid() 
+0

我相当积极,我没有在我的代码中的任何'框架'的其他定义。有什么可能导致导入无法在班级的所有模块中被识别? – user1636547

+0

@ user1636547,你能展示完整的'BuildFrames'代码吗? – falsetru

+0

找到了错误......事实证明,我在后面的'BuildFrames'中的迭代器中使用了一个变量'Frame'。我将发布代码作为答案。 – user1636547

0

您指定给Frame某处在功能

frame1 = Frame(self.window,borderwidth=2,padx=10,pady=10) 
UnboundLocalError: local variable 'Frame' referenced before assignment 

因为你是分配给它,Python知道它必须是一个局部变量,所以不看全局的。

下面是这个问题

a = 1 
def f(): 
    b = a + 1 
    a = b + 1 # If this wasn't here, the above line would use the global `a` 
f() 

如果它仍然是不明确的,包括如下(函数的其余部分)的代码的一个简单的例子,我们会指出来为你

0

问题的根源在于你正在进行全球导入。因此,框架小部件被导入为Frame

当你做for Frame in frames,你是覆盖框架类命名为Frame,因为你不能有两件事情具有相同名称的局部变量。

由于python的设计方式,它认识到你正在创建一个名为“Frame”的本地变量,然后该函数中的任何代码都会运行。所以,当你做到这一点代码:

frames.append(Frame(self.window,borderwidth=2,padx=10,pady=10)) 

...的Frame类不再存在,因为它已取代局部变量。由于您尚未为本地变量“Frame”分配值,因此会出现您所做的错误。

修复非常简单:不要创建名为“Frame”的局部变量,和/或不要执行全局导入。