2015-01-15 59 views
0

之前引用我有这样的代码:Tkinter的局部变量 'calcButton' 分配

#!/usr/bin/python 
-*- coding: utf-8 -*- 

from Tkinter import * 
from ttk import Frame, Button, Style 


class Example(Frame): 

def __init__(self, parent): 
    Frame.__init__(self, parent) 

    self.parent = parent 

    self.initUI() 

def initUI(self): 

    self.parent.title("Multiplication") 
    self.style = Style() 
    self.style.theme_use("clam") 

    self.pack(fill=BOTH, expand=1) 

    E1 = Entry(bd =5) 
    E1.place(x=0, y=0) 
    E2 = Entry(bd=5) 
    E2.place(x=125, y=0) 
    E3 = Entry(bd=5) 
    E3.place(x=62.5, y=25) 
    calcButton = Button(self, text="Button", command=calcButton.calculate) 
    calcButton.place(x=50, y=50) 
def calculate(calcButton): 
    a = E1.get() 
    b = E2.get() 
    c = E3.get() 


def main(): 

    root = Tk() 
    root.geometry("250x150+300+300") 
    app = Example(root) 
    root.mainloop() 


if __name__ == '__main__': 
    main() 

,我得到这个错误:

Traceback (most recent call last): File "E:\Python27\tkinter", line 48, in <module> main() File "E:\Python27\tkinter", line 43, in main app = Example(root) File "E:\Python27\tkinter", line 15, in __init__ self.initUI() File "E:\Python27\tkinter", line 31, in initUI calcButton = Button(self, text="Button", command=calcButton.calculate) UnboundLocalError: local variable 'calcButton' referenced before assignment

我不正确的缩进道歉,这段代码粘贴很困难。 我看过重复的问题,并尝试过他们所说的,但没有任何工作。 任何帮助表示赞赏! 谢谢。

+2

我想你想'命令= self.calculate',而不是'命令= calcButton.calculate'。 – 2015-01-15 16:44:05

+0

把那作为一个答案 – 2015-01-15 16:45:22

+0

我太懒惰,接受Ganesh Kamath的回答。 – 2015-01-15 16:46:22

回答

2
在这一行

您使用:

calcButton = Button(self, text="Button", command=calcButton.calculate) 

其中calcButton.calculate被调用时,将其分配给calcButton但还没有被宣布呢。

这也许应该是:

calcButton = Button(self, text="Button", self.calculate)