在“用Tkinter思考”教程的tt060.py中找不到我的错误

2024-10-03 17:21:03 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码是来自tutorial "Thinking in Tkinter"的源代码。你知道吗

这个文件叫做tt060.py,是一个关于事件绑定的小教程。代码下面是我从IDLE得到的回溯(Py/IDLE ver2.7.3-tkver8.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()行(no go-我把这行放回去)。然后我从事件名称中删除了self.(第12行和第17行),以查看是否有任何影响(nope)。然后,我尝试将这两个方法定义放在.bind行之前,看看这是否有任何效果(nope)。我可以让它工作,如果我只使用命令选项,但教程是关于事件绑定,所以我想知道为什么上面的代码将不工作?你知道吗


Tags: 代码inpyselfbind事件buttonroot
1条回答
网友
1楼 · 发布于 2024-10-03 17:21:03

你有缩进问题。您需要在同一列中开始每个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()

相关问题 更多 >