这是我的代码:
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():
results.insert(0, "0")
return
numbers=["7", "4", "1", "8", "5", "2", "9", "6", "3"]
for index in range(9):
Button(buttons, bg="White", text=numbers[index], width=5, height=2, command=appear).grid(padx=5, pady=5, row=index%3, column=index/3)
zero= Button(buttons, bg="White", text="0", width=5, height=2)
zero.grid(padx=5, pady=5, column=1, row=3)
functions=["-", "+", "*", "/"]
for index in range(4):
Button(buttons, bg="White", text=functions[index], width=5, height=2).grid(padx=5, pady=5, row=index%4, column=3)
equals= Button(buttons, bg="White", text="=", width=5, height=2)
equals.grid(ipadx=10, pady=5, row=5, column=1)
numbers = StringVar()
results = Entry(screen, textvariable=numbers, width=30)
results.pack()
calculator.mainloop()
计算器看起来不错,但我需要帮助,因为按下按钮会显示一个数字。正如您在我的功能中所看到的,每次按下按钮时它会显示“0”,而不是相应的数字。请帮忙。我还没有开始弄清楚如何让它做实际的数学运算,但是如果你能帮助它,那就太好了!
答案 0 :(得分:3)
您需要创建一个闭包,它返回相关的按钮数。将您的appear
功能更改为:
def appear(x):
#return an anonymous function which appends x to the "result" textentry
return lambda: results.insert(END, x)
然后更改按钮的定义,如下所示:
numbers = ["7", "4", "1", "8", "5", "2", "9", "6", "3"]
for index in range(9):
n = numbers[index]
Button(buttons, text=n, command=appear(n), ...).grid(...)
这样每个Button都有自己的函数,附加正确的数字。
在Python中,函数只是另一个对象。 command
类的Button
参数将一个函数(或任何其他可调用的东西,如类)作为参数,在按下按钮时调用该参数。 lambda
关键字创建一个我们传递给类的匿名函数。上面定义的出现方法类似于:
def appear(x):
#create a new function that displays x in the text entry and return it
def show_x():
results.insert(END, x)
return show_x
在这种情况下我们无法内联lambda:
#THIS DOESN'T WORK AS EXPECTED:
for index in range(9):
n = numbers[index]
f = lambda: results.insert(END, n)
Button(..., command = f, ...)
这不起作用,因为n
是一个局部变量,随着循环的每次迭代而变化,并在执行函数f
期间被查找 - 这意味着它将始终保持最后一个值这个案例。我们需要为值创建closure,我们在appear
函数中执行此操作。