我一直在为此奋斗了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()
感谢您的帮助,我在我的'def show_toolbar(self):'改成了'self.cancelButton.pack(side = LEFT ,padx = 2,pady = 2)'此外,我将_initUI_中的cancelButton设置为'self.cancelButton',而且这似乎已经奏效。 – level42