customfunctions.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import math
  2. import tkinter
  3. import tkinter.messagebox
  4. SCREEN = None # 设置屏幕
  5. func_input = None
  6. help = None
  7. button = None
  8. logger = None
  9. help_doc = """
  10. 请在第一个输入框输入你的函数方程,不需要输入f(x)=和y=,唯一变量是x(x为自变量)
  11. 圆周率-Pi,自然无理数-e
  12. 指数的表示符号:**,比如x**2表示x的二次方
  13. 对数的表示符号:log(a,b),其中a是真书,b是底数(没有lg和ln)
  14. 三角函数sin(),cos(),tan(),cot(),csc(),sec()
  15. 反三角函数arcsin(),arccos(),arctan()
  16. 双曲函数:sinh(),cosh(),tanh()
  17. 注意:三角函数必须带括号使用
  18. 不支持定义域选择,不支持分段函数
  19. """
  20. class CustomFuncLogger:
  21. def __init__(self):
  22. self.func = None
  23. def set(self, func):
  24. self.func = func
  25. def __call__(self, *args, **kwargs):
  26. return self.func
  27. class FunctionExpression:
  28. def __init__(self, func):
  29. self.func = func
  30. self.named_domain = {
  31. "x": 0,
  32. "Pi": math.pi,
  33. "e": math.e,
  34. "log": math.log,
  35. "sin": math.sin,
  36. "cos": math.cos,
  37. "tan": math.tan,
  38. "cot": lambda x: 1 / math.tan(x),
  39. "csc": lambda x: 1 / math.sin(x),
  40. "sec": lambda x: 1 / math.cos(x),
  41. "sinh": math.sinh,
  42. "cosh": math.cosh,
  43. "tanh": math.tanh,
  44. "asin": math.asin,
  45. "acos": math.acos,
  46. "atan": math.atan,
  47. }
  48. def __call__(self, x):
  49. self.named_domain["x"] = x
  50. return eval(self.func, self.named_domain)
  51. def custom():
  52. global func_input, help_doc, logger
  53. func_str = func_input.get().replace(" ", "")
  54. if func_str:
  55. if tkinter.messagebox.askokcancel(
  56. "提示", f"是否确认生成自定义函数:\n{func_input.get()}\n(点击取消可撤销未执行的制造函数)"
  57. ):
  58. logger.set(FunctionExpression(func_input.get()))
  59. else:
  60. logger.set(None)
  61. else:
  62. if tkinter.messagebox.askokcancel("提示", f"点击确定撤销为执行的制造函数"):
  63. logger.set(None)
  64. def get_help():
  65. tkinter.messagebox.showinfo(title="帮助", message=help_doc)
  66. def make_func():
  67. global SCREEN, func_input, help, button, logger
  68. SCREEN = tkinter.Toplevel()
  69. SCREEN.title("")
  70. SCREEN.resizable(width=False, height=False)
  71. SCREEN.geometry(f"+350+10")
  72. button = tkinter.Button(SCREEN, text="制造函数", command=custom, width=28, height=1) # 收到消息执行这个函数
  73. help = tkinter.Button(SCREEN, text="帮助", command=get_help, width=28, height=1) # 帮助菜单
  74. func_input = tkinter.Entry(SCREEN)
  75. func_input.pack(fill=tkinter.BOTH)
  76. button.pack()
  77. help.pack()
  78. logger = CustomFuncLogger()
  79. return logger