3

这是我的代码:

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”,而不是相应的数字。请帮忙。我还没有开始弄清楚如何让它做实际的数学,但如果你也能帮忙,那就太好了!

4

1 回答 1

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——这意味着在这种情况下它将始终保存最后一个值。我们需要为该值创建一个闭包,我们在appear函数中执行此操作。

于 2012-10-22T14:46:09.967 回答