使用 tkinter 小部件将数学方程式答案写入 .txt

Writing a math equation answer to .txt by using a tkinter widget

抱歉出现了奇怪的代码...它是我花了 7 个小时试图让一切正常运行的结果。

我想通过 python & tkinter 在文本文件中捕获数量、名称、价格和含增值税价格。

到目前为止,我可以成功地将数量、名称、价格写入文本,但是,我似乎无法弄清楚如何获取价格、计算价格并将答案写入文本。

我已经尝试通过多种方式绕过 int vs str 问题,包括计算价格和使用 .insert() 将答案发送到 Ent5(输入框)并使用 .get() 检索答案以写入它发短信,但我收到错误代码。 -->

"TypeError: can't multiply sequence by non-int of type 'float'"

我在进入网格之前使用 .pack() 来加速测试,我知道网格更好。

这里是一小段代码:

import tkinter as tk
from tkinter import *
import math

top = tk.Tk()
top.title('Name')
top.geometry('500x450')

v = IntVar()

Ent1 = tk.Entry(top, textvariable=v, show=None, font=('Arial', 16))
Ent2 = tk.Entry(top, show=None, font=('Arial', 16))
Ent3 = tk.Entry(top, textvariable=vT, show=None, font=('Arial', 16))
Ent5 = tk.Entry(top, show=None, font=('Arial', 16)) ###PLACEHOLDER

lbl1 = tk.Label(top, text='Quantity')
lbl2 = tk.Label(top, text='Product')
lbl3 = tk.Label(top, text='Price')

lbl1.pack()
Ent1.pack()
lbl2.pack()
Ent2.pack()
lbl3.pack()
Ent3.pack()
Ent5.pack() ###PLACEHOLDER

int_answers = int(Ent3.get())

def com2():
    km = int_answers*1.15
    Ent5.insert(0, '1.15') ### PLACEHOLDER

def com1():
    com2()
    file1 = open('eca.txt', 'a')
    L = [Ent1.get(), '   |   ' , Ent2.get(), '   |   ' , Ent3.get(), km,'\n']
    file1.writelines(L)
    file1.close()

Btn1 = tk.Button(top, command=com1, text='Ok').pack(side=BOTTOM)

top.mainloop()

提前感谢您的帮助

我无法重现所报告的错误,但确实得到了其他几个错误。

int_answers = int(Ent3.get())必须由按钮命令函数调用。我已经把它放在 com2 里面了。在问题中 int_answers 在 mainloop 运行 之前设置为零。因此,它不会随着条目的更改而修改。单击 'ok' 按钮后将其移动到代码 运行 意味着条目在更改后被读取。

import tkinter as tk
from tkinter import *
import math

top = tk.Tk()
top.title('Name')
top.geometry('500x450')

v = IntVar()
vT = IntVar() # Missing in the question.

Ent1 = tk.Entry(top, textvariable=v, show=None, font=('Arial', 16))
Ent2 = tk.Entry(top, show=None, font=('Arial', 16))
Ent3 = tk.Entry(top, textvariable=vT, show=None, font=('Arial', 16))

lbl1 = tk.Label(top, text='Quantity')
lbl2 = tk.Label(top, text='Product')
lbl3 = tk.Label(top, text='Price')

result = tk.Label( top, text = '0') # See the result in the GUI

lbl1.pack()
Ent1.pack()
lbl2.pack()
Ent2.pack()
lbl3.pack()
Ent3.pack()
result.pack()

# int_answers = int(Ent3.get())
# Move inside the com2 function

def com2():
    int_answers = int(Ent3.get())
    km = int_answers*1.15
    result.config( text = str(km)) # Show the result in the GUI
    return km   # Return the result to com1.

def com1():
    km = com2() # Otherwise com1 can't 'see' km
    file1 = open('eca.txt', 'a')
    L = [Ent1.get(), '   |   ' , Ent2.get(), '   |   ' , Ent3.get(), str(km),'\n']
    file1.writelines(L)
    print(L) # Seewhat's happening in the console.
    file1.close()

Btn1 = tk.Button(top, command=com1, text='Ok').pack(side=BOTTOM)

top.mainloop()

还有一点。我会使用更强大的 to_int 转换。如果字符串不能转换为 int 而不是引发异常,它将 return 为零。

def to_int( string):
    try: 
        return int(string)
    except ValueError:
        return 0