python中一元的操作数类型错误

2024-09-28 22:34:58 发布

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

我在用python编写计算二次公式的程序时遇到了麻烦。我是新来的,我想这将是一个好主意,学习如何使一个窗口和一些按钮。我得到的错误是:

File "quadratic.py", line 9, in quadratic
sol1 = (-(b) - (math.sqrt((b**2) - (4*a*c)))/(2*a))
TypeError: bad operand type for unary -: '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()

Tags: textgetmymathsqrtwindowlabelpack
1条回答
网友
1楼 · 发布于 2024-09-28 22:34:58

只需将saya = 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)) 

相关问题 更多 >