我在制作程序来计算python中的二次公式时遇到了麻烦。我对此并不陌生,我认为学习如何制作一个窗口和一些按钮是个好主意。我收到的错误是:
文件“ quadratic.py”,第9行,二次方
sol1 =(-(b)-(math.sqrt((b ** 2)-(4 * a * c)))/(2 * a))
TypeError:一元错误的操作数类型-:“ str”
我尝试使用括号,但这似乎不是问题。
from tkinter import *
import math
def quadratic():
a = entrya.get()
b = entryb.get()
c = entryc.get()
sol1 = (-(b) - (math.sqrt((b**2) - (4*a*c)))/(2*a))
sol2 = (-(b) + (math.sqrt((b**2) - (4*a*c)))/(2*a))
textd = Label(my_window, text="The solutions are {0} and {1}".format(sol1,sol2))
my_window = Tk()
texta = Label(my_window, text="Enter a:")
entrya = Entry(my_window)
textb = Label(my_window, text="Enter b:")
entryb = Entry(my_window)
textc = Label(my_window, text="Enter c:")
entryc = Entry(my_window)
button1 = Button(my_window, text="Calculate", command = quadratic)
texta.pack()
entrya.pack()
textb.pack()
entryb.pack()
textc.pack()
entryc.pack()
button1.pack()
my_window.mainloop()
答案 0 :(得分:1)
只需将a = entrya.get()
更改为a = float(entrya.get())
,依此类推。
def quadratic():
a = float(entrya.get())
b = float(entryb.get())
c = float(entryc.get())
sol1 = (-(b) - (math.sqrt((b**2) - (4*a*c)))/(2*a))
sol2 = (-(b) + (math.sqrt((b**2) - (4*a*c)))/(2*a))
textd = Label(my_window, text="The solutions are {0} and {1}".format(sol1,sol2))