【问题标题】:unsupported operand type(s) for ** or pow(): 'Entry' and 'int'?** 或 pow() 不支持的操作数类型:“Entry”和“int”?
【发布时间】:2013-05-28 18:02:50
【问题描述】:

我一直在尝试在 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 的初学者!

【问题讨论】:

  • 你打算做什么?
  • 使用毕达哥拉斯定理,它应该在三角形上给出 C 的边

标签: python python-3.x tkinter


【解决方案1】:

你的程序有些问题:首先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!")

【讨论】:

    【解决方案2】:

    那个错误信息很清楚。您正试图将Entry 对象提升到某种程度,而Entry 对象无法做到这一点,因为它们不是数字而是用户界面元素。相反,您需要 Entry 对象的 in 内容,即用户输入的内容,并且您可能希望将其转换为整数或浮点数。所以:

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

    【讨论】:

      猜你喜欢
      • 2017-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      相关资源
      最近更新 更多