【问题标题】:python beginner: interaction of classespython初学者:类的交互
【发布时间】:2013-05-03 05:34:12
【问题描述】:

下面的代码有什么问题?我认为由于最后一个参数,它在调用菜单栏时会引发异常?

该应用程序应该是一个简单的文本编辑器,我希望将菜单声明放在一个单独的类中。当我运行脚本时,文本字段会成功生成,但没有菜单栏。当我退出应用程序时,出现以下错误消息。

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

【问题讨论】:

    标签: python class tkinter


    【解决方案1】:

    主应用程序循环 (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()    # <----
    

    【讨论】:

      猜你喜欢
      • 2013-05-19
      • 1970-01-01
      • 2012-03-05
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 2020-12-19
      • 2019-05-30
      • 1970-01-01
      相关资源
      最近更新 更多