python - 如何在计算器中显示数字,在 Python 中使用 TKinter?

标签 python math tkinter calculator

这是我的代码:

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”,而不是相应的数字。请帮助。我还没有开始弄清楚如何让它进行实际的数学运算,但如果你也能在这方面提供帮助,那就太好了!

最佳答案

您需要创建一个闭包来返回按钮的关联编号。将您的 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 中,函数只是另一个对象。 Button 类的 command 参数将一个函数(或任何其他可调用的东西,如类)作为参数,在按下按钮时调用该函数。 lambda 关键字创建一个我们传递给类的匿名函数。上面定义的 appear 方法与此类似:

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 函数中执行。

关于python - 如何在计算器中显示数字,在 Python 中使用 TKinter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13013632/

相关文章:

Python gui - 将输入传递给脚本

python - 使用两个 pandas DataFrame 将 NaN 值替换为实际值

Python Json解码数组到字符串

python - 查找曲线之间的重叠区域(python)

python - Tkinter 侧边栏

python - macOS tkinter : how does filetypes of askopenfilename work

python - 无需停止程序即可输入

Python 问题 : AttributeError: 'dict' object has no attribute 'upper'

c++ - 计算 3 维中的相机 LookAt 位置 (DirectX)

unity-game-engine - 与 的幂相反