这是我的计算器代码。我无法弄清楚如何使+ - / *执行它们的功能......我在使用Equals函数中的If语句时想到了什么?
from Tkinter import*
calculator = Tk()
calculator.title('Calcualtor')
calculator.geometry('300x325')
screen = Frame(calculator, bd=2, width=250, height=25, relief=SUNKEN)
buttons = Frame(calculator, bd=2, width=250, height=200)
screen.grid(column=0, row=0, padx=25, pady=25)
buttons.grid(column=0, row=1, padx=25)
def appear(x):
return lambda: results.insert(END, x)
def Zero():
results.insert(END, "0")
return
def Math():
number= results.get()
results.delete(0, END)
number2=results.get()
return
def Equals():
numbers=["7", "4", "1", "8", "5", "2", "9", "6", "3"]
for index in range(9):
n=numbers[index]
Button(buttons, bg="White", text=n, width=5, height=2, command=appear(n)).grid(padx=5, pady=5, row=index%3, column=index/3)
zero= Button(buttons, bg="White", text="0", width=5, height=2, command=Zero)
zero.grid(padx=5, pady=5, column=1, row=3)
functions=["-", "+", "*", "/"]
for index in range(4):
f=functions[index]
Button(buttons, bg="White", text=f, width=5, height=2, command=Math).grid(padx=5, pady=5, row=index%4, column=3)
equals= Button(buttons, bg="White", text="=", width=5, height=2, command=Equals)
equals.grid(ipadx=10, pady=5, row=5, column=1)
numbers = StringVar()
results = Entry(screen, textvariable=numbers, width=30)
results.pack()
calculator.mainloop()
答案 0 :(得分:1)
最简单的解决方案是使用eval()
并让python为您完成所有工作。只需像对数字一样在文本条目中添加+ - / *,然后使用等于按钮来评估文本条目中的文本。
进行以下更改:
def Equals():
try:
result = eval(results.get())
except:
result = "Invalid sum"
results.delete(0, END)
results.insert(0, result)
....
Button(buttons, bg="White", text=f, width=5, height=2, command=appear(f)).grid(padx=5, pady=5, row=index%4, column=3)
您还应该禁用文本条目,以便恶意用户无法执行代码。