【问题标题】:Bad operand type for unary in pythonpython中一元的错误操作数类型
【发布时间】:2019-04-11 21:39:17
【问题描述】:

我在编写一个在 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()

【问题讨论】:

  • 错误说明了一切......您.get() 的值是字符串,而不是数字。
  • 您正在尝试使用一元否定,即。 -(负号)在字符串对象上,但字符串对象不支持。尝试转换为数字数据类型,例如float

标签: python tkinter


【解决方案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)) 

【讨论】:

    猜你喜欢
    • 2018-08-08
    • 2015-01-06
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    相关资源
    最近更新 更多