2013-11-26 33 views
-1

以下代碼是tutorial "Thinking in Tkinter"的源代碼。在「Think in Tkinter」教程中找不到tt060.py中的錯誤

該文件被稱爲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.以查看它是否有任何效果(不行)。然後,我試着在.bind行之前放置2個方法定義,以查看它是否有任何影響(nope)。我可以讓它工作,如果我只是使用命令選項,但教程是在事件綁定,所以我想知道爲什麼上面的代碼將無法正常工作?

回答

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() 
+0

感謝您捕獲那個明顯而又謙遜的錯誤。我要去做一個壁紙提醒,「自我:在嘗試修復其他語法錯誤之前,請檢查所有內容 - 兩次!」謝謝 –