2013-05-03 62 views
0

下面的代碼有什麼問題?我認爲由於最後一個參數,它調用菜單欄時會引發異常?python初學者:類的交互

應用程序應該是一個簡單的文本編輯器,我希望在一個單獨的類中有菜單聲明。當我運行腳本時,文本字段成功生成,但沒有菜單欄。當我退出應用程序時,會出現以下錯誤消息。

""" 
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: this isn't a Tk applicationNULL main window 
""" 

from 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) 

回答

5

必須在程序中的所有其他語句之後啓動主應用程序循環(window.mainloop())。當你創建菜單時,你的主窗口已經被銷燬了。

self.scrollbar.config(command=self.text.yview) 
    self.text.pack() 
    window.mainloop() # Remove this line 

... 

window = Tk()    
textfield = Textfield(window) 
menu = Menubar(window, textfield.text) 
window.mainloop() # <---- 
+0

太棒了,謝謝! – solarisman 2013-05-03 06:32:17