2017-06-21 33 views
0

我一直在爲此奮鬥了3天,但我似乎無法掌握這一點。很簡單,我試圖在按下保存按鈕時顯示(打包)取消按鈕,但它不起作用。AttributeError:''object has no attribute'' - 試圖在tkinter中隱藏/顯示元素

當我按下保存按鈕,我得到:

AttributeError: 'MainWindow' object has no attribute 'cancelButton'

我不知道這是爲什麼,我可以清楚地看到cancelButton對象是存在的。我已經閱讀了關於如何在單擊按鈕之前對象未被初始化或調用的問題,但又一次,不確定這是怎麼回事,因爲我看到屏幕上的對象,並且我可以單擊第一個按鈕。

爲了記錄在案,我想按照這個教程,在這裏貼:In Tkinter is there any way to make a widget not visible?,但我會盡力將這個例子在我的代碼,裏面有完全不同的代碼結構,我留下的機智上述錯誤。

我的代碼如下,如果有人可以幫助解釋發生了什麼。

from tkinter import * 
from PIL import Image, ImageTk 

class MainWindow(Frame): 
    def __init__(self, parent): 
     Frame.__init__(self, parent) 
     self.parent = parent 
     self.initUI() 

    def initUI(self): 
     self.parent.title("Hello World") 

     toolbar = Frame(self.parent, bd=1, relief=RAISED) 

     self.img = Image.open("Icons\save.png") 
     eimg = ImageTk.PhotoImage(self.img) 
     saveButton = Button(toolbar, text="Save ", image=eimg, compound="left", relief=RAISED, command=self.show_toolbar) 
     saveButton.image = eimg 
     saveButton.pack(side=LEFT, padx=2, pady=2) 

     self.img = Image.open("Icons\cancel.png") 
     eimg = ImageTk.PhotoImage(self.img) 
     cancelButton = Button(toolbar, text="Cancel ", image=eimg, compound="left", relief=RAISED, command=self.quit) 
     cancelButton.image = eimg 

     toolbar.pack(side=TOP, fill=X) 

     self.pack(anchor=N, side=TOP, fill=X, expand=False) 

    def show_toolbar(event): 
     print("Pressed") 
     event.cancelButton.pack(side=LEFT, padx=2, pady=2) 

def main(): 
    root = Tk() 
    # Width X Height 
    root.geometry("500x300+300+300") 
    root.update() 
    root.minsize(400, 200) 
    app = MainWindow(root) 
    root.mainloop() 

if __name__ == '__main__': 
    main() 

回答

3
event.cancelButton.pack(side=LEFT, padx=2, pady=2) 

這是問題 - 事件不會存儲部件

* FIX *

self.cancelButton = ... 然後 self.cancelButton.pack ...

+0

感謝您的幫助,我在我的'def show_toolbar(self):'改成了'self.cancelButton.pack(side = LEFT ,padx = 2,pady = 2)'此外,我將_initUI_中的cancelButton設置爲'self.cancelButton',而且這似乎已經奏效。 – level42