我对Python3完全陌生,只是在YouTube上做了一些简单的练习。
https://www.youtube.com/watch?v=nefopNkZmB4&index=3&list=PL6gx4Cwl9DGAcbMi1sH6oAMk4JHw91mC_
这是我的代码:
from tkinter import *
def iCalc(source, side):
storeObj = Frame(source, borderwidth=4, bd=4, bg="powder blue")
storeObj.pack(side=side, expand=YES, fill=BOTH)
return storeObj
def button(source, side, text, command=None):
storeObj = Button(source, text=text, command=command)
storeObj.pack(side=side, expand=YES, fill=BOTH)
return storeObj
class app(Frame):
def __init__(self):
Frame.__init__(self)
self.option_add('*Font', 'arial 20 bold')
self.pack(expand=YES, fill=BOTH)
self.master.title('Calculator')
display = StringVar()
Entry(self, relief=RIDGE, textvariable=display, justify='right', bd=30, bg="powder blue").pack(side=TOP, expand=YES,
fill=BOTH)
for clearBut in (["CE"], ["C"]):
erase = iCalc(self, TOP)
for ichar in clearBut:
button(erase, LEFT, ichar,
lambda storeObj=display, q=ichar: storeObj.set(''))
for NumBut in ("789/", "456*", "123-", "0.+"):
FunctionNum = iCalc(self, TOP)
for iEquals in NumBut:
button(FunctionNum, LEFT, iEquals,
lambda storeObj=display, q=iEquals: storeObj.set(storeObj.get() + q))
EqualsButton = iCalc(self, TOP)
for iEquals in '=':
if iEquals in "=":
btniEquals = button(EqualsButton, LEFT, iEquals)
btniEquals.bind('<ButtonRelease-1>',
lambda e, s=self, storeObj=display: s.calc(storeObj), '+')
else:
btniEquals = button(EqualsButton, LEFT, iEquals,
lambda storeObj=display, s=' %s ' % iEquals: storeObj.set(storeObj.get() + s))
def calc(self, display):
try:
display.set(eval(display.get()))
except:
display.set("ERROR")
if __name__ == '__main__':
app().mainloop()
我收到错误消息:
我做错了什么?
发布于 2017-02-07 13:23:33
由于缩进的原因,display = StringVar()
不在方法中。这意味着它是在第一次定义类时执行的。只有在创建根窗口之后,才能创建StringVar
实例。
您需要为该行及其下面的行添加更多级别的缩进。
https://stackoverflow.com/questions/42081609
复制相似问题