1

I am making a python script for data fitting of mathematical functions say, a*sin(b*x) with the given data. I am planning to input this math function externally by the user while the program is already running. I am entering this math function through an Entry or Text box in tkinter. This is totally fine, but when I am extracting data using .get() function, it returns the entered math function in string format. But this is not useful for future process of fitting. What I understood for fitting I should have a defined functional form like

def F(x,a,b):
   return a*sin(b*x)

But if get this return value from .get() Entry display, it will be a simple string of a*sin(b*x) can't use further.

Please help me for fixing this issues if any one has any suggestions. Thanks in advance. ☺️

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685

1 Answers1

0

You can use the exec keyword to run strings as python code (Its not too safe thought so be careful)

import tkinter as tk
...
Entry = tk.Entry(root)
...
def Get_Equation():
    Text = Entry.get
    result = eval(Text)

This will run the code in the global scope so if the user enters in a * sin(b * x) you just need the variables "a", "b" and "c" defined in you program for example

import tkinter as tk
...
Entry = tk.Entry(root)
...
def Get_Equation():
    Text = Entry.get

    a = 5
    b = 3
    x = 10

    result = eval(Text)
Adi Mehrotra
  • 150
  • 1
  • 7
  • Dear Adi, Thanks for the answer. It is working fine. I was also using eval() function, but couldn't use properly. Thanks again for the help. One quick follow-up, question. I understood the harmfulness of the eval function. But based on my requirements do you think anything else can be done without using eval() function or any precautions while using eval() function? – Debasish Mondal Aug 09 '20 at 06:50
  • This is not doing what you think it does: `Text = Entry.get`. It needs to be `Text = Entry.get()`. – Bryan Oakley Aug 09 '20 at 16:28
  • Using the eval function is dangerous but most of the risk can be mitigated if you remove functions you don't want the users to use. You can do this by passing in a dictionary like this: {"__builtins__": {}} to the eval function to use as the scope where you expression is being evaluated, so like eval(expression, {"__builtins__": {}}) so that the user wont have access to function that you don't want them to – Adi Mehrotra Aug 10 '20 at 08:34
  • Thank you Adi for the suggestion. – Debasish Mondal Aug 11 '20 at 12:42