首页 > 解决方案 > 我可以使用隐式或不同的方式从弧度转换为度数模式?

问题描述

我知道标题可能含糊不清,但请耐心等待细节:

我有一个使用 Tkinter 制作的计算器应用程序。我想要做的是允许用户将模式从弧度切换到度数的功能。这些是按钮的样子:

btn_Deg = tk.Button(bottom_frame, padx=16, pady=1, bd=4, fg='white',bg = 
'#666666', font=('arial', 18), width=2, height=2,text="Deg",relief='flat', 
command=lambda: convert_deg()).grid(row=1, column=0) #TODO

btn_Rad = tk.Button(bottom_frame, padx=16, pady=1, bd=4, fg='white',bg = 
'#666666', font=('arial', 18), width=2,height=2,text="Rad",relief='flat', 
command=lambda: convert_rad()).grid(row=1,column=1) #TODO

btn_Grad = tk.Button(bottom_frame, padx=16, pady=1, bd=4, fg='white',bg = 
'#666666', font=('arial', 18), width=2, height=2,text="Grad",relief='flat', 
command=lambda:convert_grad()).grid(row=1, column=2) #TODO

我想添加这个功能,因为三角函数总是返回弧度,我想要一种不使用度数(x)的方法:

sin(x) # returns result in radians!
cos(x) # radians
tan(x) # radians as well
degrees(sin(x)) # will return result in degrees
# great, but is there a way where we can do this:
sin(x) 
# and return the result in degrees instead of radians?
# I need it this way otherwise when I am on "Degree" mode, the entry bar in 
# my calculator would look like this:
degrees(sin(x))

我确定您想知道为什么不直接使用内置于数学模块中的转换方法。原因是;如果我想将每个 sin、cos 和 tan 相关函数默认为度数,那么我的应用程序将如下所示:

https://imgur.com/a/8hyUhVn

这显然是一个问题。如果用户想要转换为度数,他们不希望每次在度数模式下进行正常计算时都弹出条目中的度数(sin(x))文本。这不是真正的计算器的工作方式。

它看起来像这样的原因可能是因为输入栏都是一个字符串,并且所有文本都使用 eval 来评估该字符串。如果我尝试使用转换度 (x),那么它只会显示在我的输入栏上,正如您在上图中看到的那样。

sum_up = str(eval(self.expression)) # 其中 self.expression 是输入栏中的任何表达式!所以这就是为什么,我想知道是否有一种特殊的方法可以以某种方式将结果默认为学位,而不必这样做:

degrees(sin(x))

如果可能的话,我希望转换以某种方式是隐式的。这是因为我们在计算器上切换模式,度数转换因子必须是隐式的。

如果有人有任何建议、方法或方法可以解决这个转换问题,我将不胜感激。

标签: pythontkintercalculatordegreesradians

解决方案


推荐阅读