简体   繁体   English

如何实现 pow(x) 和 sqrt(x)?

[英]How to implement pow(x) and sqrt(x)?

I tried looking for a similar answer, but didn't find anything.我试图寻找类似的答案,但没有找到任何东西。 So here goes.所以就到这里了。

I am currently tasked with creating a simple calculator with a GUI in Python using the tkinter tools.我目前的任务是使用 tkinter 工具在 Python 中创建一个带有 GUI 的简单计算器。

I was almost done when I ran into some problems implementing pow(x) and sqrt(x) and having them work properly.当我在实现 pow(x) 和 sqrt(x) 并让它们正常工作时遇到一些问题,我几乎完成了。

This is the function I used for my operand buttons:这是我用于操作数按钮的函数:

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

This worked fine for all the simple stuff like '+':这适用于所有简单的东西,比如“+”:

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

But now I still need to add pow and sqrt by importing from math and connect them to the buttons.但是现在我仍然需要通过从 math 导入并将它们连接到按钮来添加 pow 和 sqrt。 I tried using the same "press" function, but with sqrt I am getting a ValueError.我尝试使用相同的“按下”功能,但是使用 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 Error Code: TypeError: 'Button' object is not callable sqrt 错误代码: TypeError:“按钮”对象不可调用

Equals:等于:

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 = ""

I would really apreciate some advice.我真的很感激一些建议。 Thanks!谢谢! GUI图形用户界面

The problem is that you're replacing the built-in sqrt() function when you do:问题是您在执行以下操作时正在替换内置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)

Now the name sqrt refers to your button, not the function.现在,名称sqrt指的是您的按钮,而不是函数。 Change the variable name, like you do for the pow button.更改变量名称,就像对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)

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

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