class - python beginner: interaction of classes -
what problem in below code? think due last argument throws exception when calling menubar?
the app supposed simple text editor , want have menu declaration in separate class. when run script, textfield gets generated successfully, without menubar. when quit application, following error message occurs.
""" traceback (most recent call last): file "editor_play.py", line 41, in <module> menu = menubar(window, textfield.text) file "editor_play.py", line 20, in __init__ menubar = menu(window) file "/system/library/frameworks/python.framework/versions/2.7/lib/python2.7/lib-tk/tkinter.py", line 2580, in __init__ file "/system/library/frameworks/python.framework/versions/2.7/lib/python2.7/lib-tk/tkinter.py", line 1974, in __init__ _tkinter.tclerror: isn't tk applicationnull main window """ tkinter import * import tkfiledialog class textfield(object): def __init__(self, window): self.window = window window.title("text editor") self.scrollbar = scrollbar(window) self.scrollbar.pack(side="right",fill="y") self.text = text(window,yscrollcommand=self.scrollbar.set) self.scrollbar.config(command=self.text.yview) self.text.pack() window.mainloop() class menubar(object): def __init__(self, window, text): self.window = window self.text = text menubar = menu(window) filemenu = menu(menubar) filemenu.add_command(label="load",command=self.load) filemenu.add_command(label="save as",command=self.saveas) menubar.add_cascade(label="file",menu=filemenu) window.config(menu=menubar) def load(self): self.file = tkfiledialog.askopenfile() self.text.delete(1.0, end) if self.file: self.text.insert(1.0, self.file.read()) def saveas(self): self.file = tkfiledialog.asksaveasfile() if self.file: self.file.write(self.text.get(1.0, end)) window = tk() textfield = textfield(window) menu = menubar(window, textfield.text)
main application loop (window.mainloop()
) must started after other statements in program. when create menu, main window destroyed.
self.scrollbar.config(command=self.text.yview) self.text.pack() window.mainloop() # remove line ... window = tk() textfield = textfield(window) menu = menubar(window, textfield.text) window.mainloop() # <----
Comments
Post a Comment