繁体   English   中英

**或pow()不支持的操作数类型:'Entry'和'int'?

[英]unsupported operand type(s) for ** or pow(): 'Entry' and 'int'?

我一直在尝试在Python 33上使用Tkinter制作毕达哥拉斯定理计算器,但是我遇到了一个小问题。

这是我的代码-

from tkinter import *
import math

root = Tk()

L1 = Label(root, text="A = ")
L1.pack()

E1 = Entry(root, bd =5)
E1.pack()

L2 = Label(root, text="B = ")
L2.pack()

E2 = Entry(root, bd =5)
E2.pack()

asq = E1**2
bsq = E2**2

csq = asq + bsq
ans = math.sqrt(csq)

def showsum():
    tkMessageBox.showinfo("Answer =", ans)

B1 = tkinter.Button(root, text="Click This To Calculate!", command = showsum())
B1.pack()

root.mainloop()

这是我的错误信息-

Traceback (most recent call last):
  File "C:/Users/Dale/Desktop/programming/Python/tkinterpythagoras.py", line 18, in     <module>
    asq = E1**2
TypeError: unsupported operand type(s) for ** or pow(): 'Entry' and 'int'

请不要对我粗暴。 我是Tkinter的完整入门者!

您的程序中存在一些问题:首先, E1E2是Entry小部件,而不是数字,因此必须首先检索该值:

try:
    val = int(E1.get())
except ValueError:
    # The text of E1 is not a valid number

其次,在Button的命令选项中,您正在调用showsum()函数,而不是传递引用:

B1 = Button(root, ..., command=showsum)  # Without ()

此外,此函数始终显示先前计算出的相同结果,因此您应在此函数中而不是之前检索小部件的值。 最后,使用from tkinter import * Button在全局命名空间中,因此您应该在它之前删除对tkinter的引用。

因此,最终showsum可能与此类似:

def showsum():
    try:
        v1, v2 = int(E1.get()), int(E2.get())
        asq = v1**2
        bsq = v2**2
        csq = asq + bsq
        tkMessageBox.showinfo("Answer =", math.sqrt(csq))
    except ValueError:
        tkMessageBox.showinfo("ValueError!")

该错误消息非常清楚。 您试图将Entry对象提升到某种程度,而您不能通过Entry对象来实现,因为它们不是数字而是用户界面元素。 相反,你想要的是 Entry对象,即什么样的用户输入,你可能希望将其转换为整数或浮点数。 所以:

asq = float(E1.get()) ** 2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM