0

这是我的计算器代码。我不知道如何使 + - / * 执行它们的功能......我在想我的 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()
4

1 回答 1

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)

您还应该禁用文本输入,以便恶意用户无法执行代码。

于 2012-10-24T01:25:11.250 回答