从 Entry 保存输入历史

Saving input history from Entry

好吧,我正在 python 中构建一个计算器,到目前为止只构建了求和函数。建筑功能不是我所坚持的。我正在构建我的计算器,试图复制 Windows 10 UWP 计算器行为。 我的代码有点做同样的事情,它一次只接受一个输入,并使用当前输入和上一个答案计算总和。这是我写的代码:

import tkinter as tk
root = tk.Tk()

ans = 0
tocalculate = tk.IntVar()

entry = tk.Entry(root, textvariable=tocalculate)

entry.pack()

def Sum():
    global ans
    ans+=tocalculate.get()
    tocalculate.set(ans)

ansLabel = tk.Label(root, textvariable=tocalculate)
ansLabel.pack()

button_calc = tk.Button(root, text="Calculate", command=Sum)
button_calc.pack()

root.mainloop()

它有一些怪癖,但逻辑是可行的。现在,我想问的问题是,在 Windows 10 UWP 计算器中,当您开始计算时,它会保存您的历史记录并将其显示在上面的标签中(就像我附上的屏幕截图一样)。我如何使用 Python 和 Tkinter 做到这一点? Screenshot of UWP Calculator to show you what I mean

我对这一切还很陌生,所以我们将不胜感激。

只需添加另一个全局变量 var 以字符串格式存储计算,而不是 ansLabel 显示 tocalculate set它显示 var

import tkinter as tk
root = tk.Tk()

ans = 0
var =''   # <-- this will store the calculations in string format
tocalculate = tk.IntVar()
toshow = tk.IntVar()  # <-- This label will display history i.e contents of var

entry = tk.Entry(root, textvariable=tocalculate)

entry.pack()

def Sum():
    global ans
    global var
    v=tocalculate.get()
    var = var+"+"+str(v) 
    ans += v
    tocalculate.set(ans)
    toshow.set(var)

ansLabel = tk.Label(root, textvariable=toshow)
ansLabel.pack()

button_calc = tk.Button(root, text="Calculate", command=Sum)
button_calc.pack()

root.mainloop()

另外,修改了上面的Sum函数,它将var = previous value of var + new value entered in textbox存储为字符串格式,用于减法将+替换为-,其他的也一样

以上代码给出