基本上我现在正在学习 Python,所以我只是使用其他人的模板并编辑它们。到目前为止,我已经了解到 Python 中的缩进非常挑剔。但是我被卡住了,我认为我的所有内容都正确缩进并正确定义,但我的控制台中仍然出现此错误。(视窗)
(是的,我知道它还没有完成)
"...\documents\python_files>python calc.py
Traceback (most recent call last):
File "calc.py", line 20, in <module>
class Calculator(wx.Dialog):
File "calc.py", line 46, in Calculator
b = wx.Button(self, -1, label)
NameError: name 'self' is not defined"
这是我的代码(我想我把它以代码格式放在这里):
# -*- coding: utf-8 -*-
from __future__ import division
__author__ = 'Sean'
__version__ = '0.0.2'
#Calculator GUI:
# ____________v
#[(][)][^][log]
#[C][±][√][%]
#[7][8][9][/]
#[4][5][6][*]
#[1][2][3][-]
#[0][.][+][=]
import wx
from math import *
class Calculator(wx.Dialog):
'''Main calculator dialog'''
def __init__(self):
title = 'Calculator version %s' % __version__
wx.Dialog.__init__(self, None, -1, title)
sizer = wx.BoxSizer(wx.VERTICAL) # Main vertical sizer
# ____________v
self.display = wx.ComboBox(self, -1)
sizer.Add(self.display, 0, wx.EXPAND)
#[(][)][^][log]
#[C][±][√][%]
#[7][8][9][/]
#[4][5][6][*]
#[1][2][3][-]
#[0][.][+][=]
gsizer = wx.GridSizer(4,6)
for row in (("(",")","^","log"),
("C","±","√","%"),
("7", "8", "9", "/"),
("4", "5", "6", "*"),
("1", "2", "3", "-"),
("0", ".", "+", "=")):
for label in row:
b = wx.Button(self, -1, label)
gsizer.Add(b)
self.Bind(wx.EVT_Button,self.OnButton, b)
sizer.Add(gsizer, 1, wx.EXPAND)
b = wx.Button(self, -1, "=")
self.Bind(wx.EVT_BUTTON, self.OnButton, b)
sizer.Add(b, 0, wx.EXPAND)
self.equal = b
self.SetSizer(sizer)
sizer.Fit(self)
self.CenterOnScreen()
def OnButton(self, evt):
'''Handle button click event'''
label = evt.GetEventObject().GetLabel()
if label == '=':
try:
compute = self.display.GetValue()
if not compute.strip():
return
result = eval(compute)
self.display.Insert(compute, 0)
self.display.SetValue(str(result))
except Exception as err:
wx.LogError(str(err))
return
elif label == 'C':
self.display.SetValue('')
else:
self.display.SetValue(self.display.GetValue() + label)
self.equal.SetFocus()
if __name__ == '__main__':
app = wx.PySimpleApp()
dlg = Calculator()
dlg.ShowModal()
dlg.Destroy()