2
$\begingroup$


I'm new to Mathematica and I'm trying to learn to write some basic code to create a DialogInput in which the user writes the function to plot.

I'd like to understand how packages work, so I'm trying to move the function GuessTheFunctionGUI in the package, leaving just the call of the package function in the notebook.

When I leave the GuessTheFunctionGUI in the notebook everything works fine, but at the moment when I run the code and write the function in the InputField then the Plot is not dynamically updated (to tell the truth, nothing is plotted).

Any tips on what I'm messing? My idea is that the Private scope of the function doesn't allow updating dynamically the value of the math function in the plot.

Notebook.nb

Get["Package.wl"];

ButtonBox["Start", Appearance -> Automatic, 
  ButtonFunction :> 
   FrontEndExecute[FrontEndToken["EvaluateNotebook"]], 
  Evaluator -> Automatic, Method -> "Preemptive"] // DisplayForm
GuessTheFunctionGUI[];

Package.wl

BeginPackage["Package`"];

GuessTheFunctionGUI::usage = "GuessTheFunctionGUI[]";

Begin["`Private`"];
SetDirectory[NotebookDirectory[]];

GuessTheFunctionGUI[] := DynamicModule[{func = ""},
  DialogInput[
  Column[{
    InputField[Dynamic[func], String, FieldHint -> "Insert the function here"],
    Dynamic@Plot[ToExpression[func], {x, -10, 10}, PlotStyle -> Blue, 
      AxesLabel -> {"x", "y"}, PlotLabel -> "Function plot", ImageSize -> Medium]
    }],
    WindowTitle -> "Interactive Plot", WindowSize -> {500, 500}, 
    WindowMargins -> {{Automatic, 0}, {0, Automatic}}, 
    WindowElements -> {"VerticalScrollBar", "HorizontalScrollBar", "StatusArea"}
  ]]
  
End[];
EndPackage[];

EDIT: I don't know if this is relevant too, but the version of Mathematica that I'm using is the following:

$Version
"14.0.0 for Microsoft Windows (64-bit) (December 13, 2023)"
$\endgroup$
2
  • $\begingroup$ I confirm this is also behaving the same on my machine, same version $\endgroup$ Commented May 10 at 2:46
  • $\begingroup$ Your idea was very much on the right track! I noticed your code did still work when using a constant instead of x, so that led me to the answer I posted. $\endgroup$ Commented May 10 at 3:03

1 Answer 1

0
$\begingroup$

When in the package I get this if i try and plot x:

enter image description here

But this works (SymbolTools` is my own package I put this in to test):

enter image description here

Replacing Plot[ToExpression[func], {x, -10, 10} with Plot[ToExpression[func], {Global`x, -10, 10} in the definition makes it work as desired!

$\endgroup$
1
  • $\begingroup$ An entirely separate question would be how to prevent the kernel from crashing when I close the window... $\endgroup$ Commented May 10 at 2:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.