【问题标题】:Saving input history from Entry从条目保存输入历史
【发布时间】:2018-07-21 09:19:19
【问题描述】:

好吧,我正在用 python 构建一个计算器,到目前为止只构建了 sum 函数。构建功能并不是我所坚持的。我正在构建我的计算器,试图复制 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

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

【问题讨论】:

  • 我认为这太宽泛了。你到底坚持展示历史的哪一部分?问那个。

标签: python tkinter calculator


【解决方案1】:

只需添加另一个全局变量 var 用于以字符串格式存储计算,而不是 ansLabel 显示 tocalculate 将其设置为显示 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,用于将 + 替换为 - 和其他人一样明智

以上代码给出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 2017-11-28
    • 2010-11-01
    • 1970-01-01
    • 2011-04-15
    相关资源
    最近更新 更多