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

标签 python python-3.x tkinter

我一直在尝试在 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

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

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

此外,此函数始终显示先前计算的相同结果,因此您应该在此函数中而不是之前检索小部件的值。最后,带有 from tkinter import * 按钮位于全局命名空间中,因此您应该删除对它之前的 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!")

关于python - ** 或 pow() 不支持的操作数类型 : 'Entry' and 'int' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16798581/

相关文章:

Emacs:如何在 python 模式下自动启动 python 解释器?

Python 使用全局 vs 指定模块

python - 为什么这种并行搜索和替换没有使用 100% 的 CPU?

python - 枕头 : File not found

python - 在 tkinter 中查找窗口的坐标

python - 导入错误 : cannot import name

python - 如何在 Flask-Admin 中将方法中的访问与 BaseModelView 类分开

将正则表达式解析为 AST 的 Python 库?

python - 在Python3中打印涉及英语和日语文本的右对齐表格列

python - Tkinter 网格填充空白空间