不了解此类型错误的原因:不支持的操作数类型

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

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

我已经写了这段代码,不知道是什么问题。它应该是一个弹出窗口,可以使用Python中的二次公式求解二次方程ax^2+bx+c=0

from tkinter import *

root = Tk()

a= Entry(root, width=50, bg="white",
fg="black",
borderwidth=3.5,)
a.pack()
a.get()

b= Entry(root, width=50, bg="white",
fg="black",
borderwidth=3.5,)
b.pack()
b.get()

c= Entry(root, width=50, bg="white",
fg="black",
borderwidth=3.5,)
c.pack()
c.get()

Cscore=c.get()
Bscore=b.get()
Ascore=a.get()

#ax^2 + bx + c = 0
import math

def slove(Ascore,Bscore,Cscore):
    d = math.sqrt((Bscore**2)- 4*Ascore*Cscore)
    x1 = (-Bscore - d) / (2 * Ascore)
    x2 = (-Bscore + d) / (2 * Ascore)
    return x1, x2

x1, x2 = slove (Ascore ,Bscore ,Cscore)
#print("x1")
#print(x1)
#print("x2")
#print(x2)

def myClick():

    myLabel3 = Label(root,
    text="Megoldás   " + x1 + x2, borderwidth=15)
    myLabel3.pack()

myButton = Button(root, text="solve",
 padx=10, pady=5, command=myClick,
 fg= "black" , bg= "white" )

myButton.pack()

root.mainloop()

这是我在终端上运行后得到的错误消息:

Traceback (most recent call last):
  File "c:\matek\math_sqrtupdate.py", line 43, in <module>
    x1, x2 = slove (Ascore ,Bscore ,Cscore)
  File "c:\matek\math_sqrtupdate.py", line 37, in slove
    d = math.sqrt((Bscore**2)- 4*Ascore*Cscore)
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

以前,它不是'str'而是'Entry',我用Ascore,Bscore,Cscore取消了它,但它不是'Entry'而是'str'。我不知道该怎么做


Tags: getmathrootpackbgblackentryx1
2条回答

您的代码有很多问题,但是TypeError是由这组语句引起的:

Cscore=c.get()
Bscore=b.get()
Ascore=a.get()

因为Entry小部件的内容是字符串,而不是执行计算所需的浮点值。您还在错误的时间执行get()方法-在单击solve按钮之前不应该执行,因此我已经有效地将它们移动到了myClick()回调函数中

为了帮助纠正这个问题,我添加了一个名为get_numeric_value()的助手函数,对作为参数传递给它的Entry进行转换

除此之外,我还修复了其他几个问题,使其能够运行注意:如果你打算使用这种语言,我强烈建议你阅读并开始跟随PEP 8 - Style Guide for Python Code

import math
from tkinter import *

root = Tk()

a = Entry(root, width=50, bg="white",
          fg="black",
          borderwidth=3.5,)
a.pack()

b = Entry(root, width=50, bg="white",
          fg="black",
          borderwidth=3.5,)
b.pack()

c = Entry(root, width=50, bg="white",
          fg="black",
          borderwidth=3.5,)
c.pack()

def solve(Ascore, Bscore, Cscore):
    """ Solve quadratic equation: ax^2 + bx + c = 0
        and return solution values.
    """
    try:
        d = math.sqrt((Bscore**2)- 4*Ascore*Cscore)
        x1 = (-Bscore - d) / (2 * Ascore)
        x2 = (-Bscore + d) / (2 * Ascore)
        return x1, x2
    except ValueError:
        return math.nan, math.nan

def get_numeric_value(entry):
    """ Retrieve Entry's string contents and convert it to a float. """
    v = entry.get()
    return float(v) if v else 0.0

# Alternative using "walrus" operator added in Python 3.8.
#def get_numeric_value(entry):
#    """ Retrieve Entry's string contents and convert it to a float. """
#    return float(v) if (v := entry.get()) else 0.0

def myClick():
#    Ascore = get_numeric_value(a)
#    Bscore = get_numeric_value(b)
#    Cscore = get_numeric_value(c)
    Ascore, Bscore, Cscore = map(get_numeric_value, (a, b, c))

    x1, x2 = solve(Ascore, Bscore, Cscore)
    myLabel3 = Label(root, borderwidth=15,
                     text=f"Megoldás   {x1:.6f}, {x2:.6f}")
    myLabel3.pack()

myButton = Button(root, text="solve",
                  padx=10, pady=5, command=myClick,
                  fg= "black", bg="white")
myButton.pack()

root.mainloop()

您必须确保所有Ascore、Bscore和Cscore都是数字(而不是字符串)。看起来Bscore可能是一个字符串。下面是浮动与字符串的演示:

>>> Bscore = 2.0   
>>> Bscore**2    
4.0
>>> Bscore = '2.0' 
>>> Bscore**2      
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
>>>

相关问题 更多 >