Python错误(初学者)
我最近在学习Python,主要是通过一些在线教程,前几天进展得还不错,但突然遇到了一个我解决不了的错误。
今天我用的网站是 http://wiki.wxpython.org/Getting%20Started
我已经顺利学到了关于sizers的内容,没遇到太多麻烦。但是当我尝试运行教程中的一个程序时,出现了以下错误:
错误追踪(最近的调用在最前面):
文件 "C:/Python27/test.pyw",第4行,
类 MainWindow(wx.Frame):
文件 "C:/Python27/test.pyw",第8行,在 MainWindow 中
wx.Frame.init(self,parent,title=title,size=(200,-1))
NameError: 名称 'self' 未定义
import wx
import os
class MainWindow(wx.Frame):
def __init__(self,parent,title):
self.dirname=''
wx.Frame.__init__(self,parent,title=title,size=(200,-1))
self.control=wx.TextCtrl(self,style=wx.TE_MULTILINE)
self.CreateStatusBar()
filemenu=wx.Menu()
menuOpen=filemenu.Append(wx.ID_OPEN,'&Open','Open a file to edit')
menuAbout=filemenu.Append(wx.ID_ABOUT,"&About","Information about this program")
menuExit=filemenu.Append(wx.ID_EXIT,"E&xit","Terminate the program")
menuBar=wx.MenuBar()
menuBar.Append(filemenu,'&File')
self.SetMenuBar(menuBar)
self.Bind(wx.EVT_MENU,self.OnOpen,menuOpen)
self.Bind(wx.EVT_MENU,self.OnExit,menuExit)
self.Bind(wx.EVT_MENU.self.OnAbout,menuAbout)
self.sizer2=wx.BoxSizer(wx.HORIZONTAL)
self.buttons=[]
for i in range(0,6):
self.buttons.append(wx.Button(self,-1,'button &'+str(i)))
self.sizer2.Add(self.buttons[i],1,wx.EXPAND)
self.SetSizers(self.sizer)
self.SetAutoLayout(1)
self.sizer.Fit(self)
self.Show()
def OnAbout(self,e):
dlg=wx.MessageDialog(self,'A sample editor \n in wxPython', 'About sample editor', wx.OK)
dlg.ShowModal()
dlg.Destroy()
def OnExit(self,e):
self.Close(True)
def OnOpen(self,e):
dlg=wx.FileDialog(self,"choose a file", self.dirname,"","*.*",wx.OPEN)
if dlg.ShowModal() == wx.ID_OK:
self.filename=dlg.GetFilename()
self.dirname=dlg.GetDirectory()
f=open(os.path.join(self.dirname,self.filename),'r')
self.control.SetValue(f.read())
f.close()
dlg.Destroy()
app=wx.App(False)
frame=MainWindow(None,'Sample editor')
app.MainLoop()
我已经为此努力了大约一个小时,重打和检查了好几遍。如果能得到一些建议或者其他教程的帮助,我会非常感激。另外,有没有什么常见错误的列表可以参考呢?
2 个回答
0
你有一个缩进错误:从第8行开始的所有内容都应该缩进,和前面的行对齐。
3
从 wx.Frame.__init__(...)
开始,到下一个 def
之前的所有内容,都必须再缩进一个层级。