从条目保存输入历史记录

2024-09-27 17:38:42 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我正在用python构建一个计算器,到目前为止只构建了sum函数。我不喜欢构建函数。我正在构建我的计算器,试图复制windows10uwp计算器的行为。 我的代码与此相同,它一次只接受一个输入,并使用当前输入和上一个答案计算总和。下面是我写的代码:

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()

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

我对这一切都很陌生,所以任何和所有的帮助都将被感激。在


Tags: 函数代码calcbuttonroot计算器packtk
1条回答
网友
1楼 · 发布于 2024-09-27 17:38:42

只需添加另一个全局变量var以字符串格式存储计算结果,并将其设置为displayvar

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函数,它将以字符串格式存储{},对于减法,用-替换{},对于其他函数也一样

上面的代码给出this

相关问题 更多 >

    热门问题