嗨我正在做一个计算器,但我GT预期意图阻止我试图删除该部分,当它出来的错误但没有运气任何帮助将不胜感激。也可以有人教我如何使用lopp或添加一个while循环在这段代码中?
from tkinter import *
from tkinter.font import Font
def button(frame, text, command=None):
ft = Font(family=('Verdana'), size=14)
return Button(frame, text=text, font=ft, width=3, command=command)
def frame(frame, side=LEFT, bg="black"):
f = Frame(frame, background=bg, padx=5, pady=5)
f.pack(side=side, expand=YES, fill=BOTH)
return f
class App:
def __init__(self, tk):
ft = Font(family=('Verdana'), size=14)
main = frame(tk)
l_frame = frame(main)
r_frame = frame(main)
calc_frame = frame(l_frame)
self.input = Entry(calc_frame, font=ft, width=15, background="white")
self.input.pack(side=TOP)
self.input.bind_all('<BackSpace>', self.cleanInput)
self.btn_frame = frame(calc_frame)
x, y = 0, 0
for key in ("()%C", "+-*/", "1234", "5678", "90.="):
for c in key:
if c == "=":
btn = button(self.btn_frame, c, self.equalAction)
elif c == "C":
btn = button(self.btn_frame, c, self.cleanAction)
else:
btn = button(self.btn_frame, c, lambda i=c: self.input.insert(INSERT, i))
btn.grid(row=x, column=y)
y += 1
x += 1
y = 0
self.log = Text(r_frame, font=Font(family=('Verdana'), size=10), width=25, height=14, background="yellow")
self.log.pack(side=RIGHT)
def cleanAction(self):
self.input.delete(0, END)
def cleanInput(self, event):
self.input.delete(0, END)
self.log.delete(1.0, END)
else:
btn = button(self.btn_frame, c, lambda i=c: self.input.insert(INSERT, i))
main.bind_all(c, lambda event, i=c:self.input.insert(INSERT, i))
def equalAction(self):
tmp = self.input.get()
try:
result = tmp + "=" + str(eval(tmp))
self.log.insert(1.0, result + "\n");
print(result)
except Exception:
self.log.insert(1.0, "Wrong expression\n");
if __name__ == '__main__':
root = Tk()
root.title("Calculator")
root.geometry()
app = App(root)
root.mainloop()
答案 0 :(得分:2)
预期的区块在
的行中def cleanAction(self):
self.input.delete(0, END)
应该是
def cleanAction(self):
self.input.delete(0, END)
Python要求您始终很好地缩进代码,因为缩进是语法的一部分。在上面的例子中,第二行是在定义的函数cleanAction()中执行的命令。解释器在定义函数之后需要一行,并告诉你它。
关于循环:最好的方法是从https://wiki.python.org/moin/ForLoop
开始答案 1 :(得分:1)
def cleanAction(self):
self.input.delete(0, END)
你的缩进开始搞砸了。 cleanInput
也搞砸了。它缩进了,并且else
没有if
。