def btnSquareRoot(self):
result = False
current = math.sqrt(text_Input)
text_Input.set(current)
这是我尝试使用的代码,但我不能,因为
text_Input
是一个字符串变量
我是一个初学者,这就是为什么对我来说很难做到这一点,但我的想法是以某种方式转换它,但我不知道如何
将text_input转换为int或float,然后你就可以找到平方根了。
math.sqrt(int(text_Input)) or math.sqrt(float(text_Input))
要将字符串转换为浮点数,您可以使用 float 函数,如下所示:
def btnSquareRoot(self):
result = False
current = math.sqrt(float(text_Input))
text_Input.set(current)
您可以使用
str(i)
将浮点数转换为字符串,使用 float(x)
将字符串转换为浮点数。所以你的代码应该是 text_Input.set(str(current))
而不是 text_Input.set(current)
,并且 math.sqrt(float(text_Input.get()))
而不是 math.sqrt(text_Input)
。
导入数学
def 计算器(): print("简单计算器")
while True:
try:
expression = input("Enter an expression (or 'exit' to quit): ")
if expression.lower() == 'exit':
print("Exiting the calculator. Goodbye!")
break
result = evaluate_expression(expression)
print("Result:", result)
except Exception as e:
print("Error:", e)
def 评估表达式(表达式): 如果表达式中包含“sqrt”: # 从表达式中提取数字 number = float(表达式.replace('sqrt(', '').replace(')', '')) 结果 = math.sqrt(数字) 返回结果 返回 eval(表达式) 计算器()