在“Thinking in Tkinter”教程中的tt060.py中找不到我的错误

时间:2013-11-26 10:56:39

标签: python python-2.7 user-interface tkinter python-idle

以下代码是tutorial "Thinking in Tkinter"的源代码。

该文件名为tt060.py,是一个关于事件绑定的小教程。代码下面是我从IDLE获得的回溯(Py / IDLE ver2.7.3 - Tk ver 8.5)。以下代码有什么问题导致它无法正确运行并出错?

from Tkinter import *

class MyApp:
    def __init__(self, parent):
        self.myParent = parent
        self.myContainer1 = Frame(parent)
        self.myContainer1.pack()

        self.button1 = Button(self.myContainer1)
        self.button1.configure(text="OK", background= "green")
        self.button1.pack(side=LEFT)
        self.button1.bind("<Button-1>", self.button1Click)  #

        self.button2 = Button(self.myContainer1)
        self.button2.configure(text="Cancel", background="red")
        self.button2.pack(side=RIGHT)
        self.button2.bind("<Button-1>", self.button2Click)  #

        def button1Click(self, event):
            if self.button1["background"] == "green":
                self.button1["background"] = "yellow"
            else:
                self.button1["background"] = "green"

        def button2Click(self, event):
            self.myParent.destroy()

root = Tk()
myapp = MyApp(root)
root.mainloop()

回溯:

Traceback (most recent call last):
  File "C:/Current/MY_PYTHON/ThinkingInTkinter/tt060.py", line 29, in <module>
    myapp = MyApp(root)
  File "C:/Current/MY_PYTHON/ThinkingInTkinter/tt060.py", line 12, in __init__
    self.button1.bind("<Button-1>", self.button1Click)  #
AttributeError: MyApp instance has no attribute 'button1Click'

我按照教程的建议尝试的第一件事是注释root.mainloop()行(没有去 - 我把线放回去)。然后,我从事件名称(第12行和第17行)中删除了self.,看看是否有任何影响(nope)。然后我尝试在.bind行之前放置2个方法定义,看看是否有任何影响(nope)。如果我只使用命令选项,我可以使它工作,但教程是关于事件绑定的,所以我想知道为什么上面的代码不起作用?

1 个答案:

答案 0 :(得分:1)

你有缩进问题。您需要在同一列开始每个def

from Tkinter import *

class MyApp:
    def __init__(self, parent):
        self.myParent = parent
        self.myContainer1 = Frame(parent)
        self.myContainer1.pack()

        self.button1 = Button(self.myContainer1)
        self.button1.configure(text="OK", background= "green")
        self.button1.pack(side=LEFT)
        self.button1.bind("", self.button1Click)  #

        self.button2 = Button(self.myContainer1)
        self.button2.configure(text="Cancel", background="red")
        self.button2.pack(side=RIGHT)
        self.button2.bind("", self.button2Click)  #

    def button1Click(self, event):
        if self.button1["background"] == "green":
           self.button1["background"] = "yellow"
        else:
           self.button1["background"] = "green"

    def button2Click(self, event):
        self.myParent.destroy()

root = Tk()
myapp = MyApp(root)
root.mainloop()