【问题标题】:How to implement pow(x) and sqrt(x)?如何实现 pow(x) 和 sqrt(x)?
【发布时间】:2020-04-19 14:33:10
【问题描述】:

我尝试寻找类似的答案,但没有找到任何东西。就这样吧。

我目前的任务是使用 tkinter 工具在 Python 中创建一个带有 GUI 的简单计算器。

当我在实现 pow(x) 和 sqrt(x) 并让它们正常工作时遇到一些问题时,我几乎完成了。

这是我用于操作数按钮的函数:

def press(num):
   global expression
   expression = expression + str(num)
   equation.set(expression)

这适用于所有简单的东西,如“+”:

plus = Button(gui, text=' + ', fg='orange', bg='white', command=lambda: press("+"), height=1, width=7)

但现在我仍然需要通过从数学导入来添加 pow 和 sqrt 并将它们连接到按钮。我尝试使用相同的“按下”功能,但使用 sqrt 我得到一个 ValueError。

powx = Button(gui, text=' pow(x) ', fg='orange', bg='white', command=lambda: press("pow("), height=1, width=7)
powx.grid(row=4, column=4)
sqrt = Button(gui, text=' sqrt(x) ', fg='orange', bg='white', command=lambda: press("sqrt("), height=1, width=7)
sqrt.grid(row=5, column=4)

sqrt 错误代码: TypeError: 'Button' 对象不可调用

等于:

def equalpress():
    try:
        global expression
        total = str(eval(expression))
        equation.set(total)
        expression = ""

    except ZeroDivisionError: 
        equation.set(" Cant divide through Zero! ")
        expression = ""

    except SyntaxError: 
        equation.set(" SyntaxError! ")
        expression = ""

我真的很感激一些建议。谢谢! GUI

【问题讨论】:

  • press() 放置左括号,但何时添加右括号?

标签: python user-interface tkinter calculator math.sqrt


【解决方案1】:

问题是你替换了内置的sqrt() 函数:

sqrt = Button(gui, text=' sqrt(x) ', fg='orange', bg='white', command=lambda: press("sqrt("), height=1, width=7)
sqrt.grid(row=5, column=4)

现在名称sqrt 指的是您的按钮,而不是功能。更改变量名称,就像对 pow 按钮所做的那样。

sqrtx = Button(gui, text=' sqrt(x) ', fg='orange', bg='white', command=lambda: press("sqrt("), height=1, width=7)
sqrtx.grid(row=5, column=4)

【讨论】:

  • 哦,是的,这绝对解决了 sqrt 问题。我觉得很愚蠢,因为我花了 2 个小时才意识到这一点。谢谢!
猜你喜欢
  • 2017-07-14
  • 1970-01-01
  • 2014-10-23
  • 1970-01-01
  • 1970-01-01
  • 2021-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多