Picture Buttons

November 9 homework example
Jim Mahoney

Code

To use this, you'll need
	(a) a cell whose CellTags has been set to some name of your choice, and
	(b) buttons that call the writeGraphics function with a Graphics object and the name of the cell.

The raw Mathematica code for the button might look something like this.
(You'd need to use the Show Expression menu choice under the Format menu to open up a cell to a place where you could type this.
 Or you could use the Edit / Expression Input / Insert Raw Expression... menu command.)
 
	ButtonBox[
        "Show Jim's Picture",
        ButtonFunction :> writeGraphics[ jimsPicture, "thePicture"],
        ButtonEvaluator->Automatic,
        Active->True,
        ButtonStyle->None]

(* Set the working directory to the same as where this notebook lives.
   You could do this by hand with SetDirectory["/some/path/"] ;
   this command just lets you put the png file to be loaded next
   in the same directory as this notebook. *)
SetDirectory[
 DirectoryName[
   ToFileName["FileName"/.NotebookInformation[SelectedNotebook[]]]]];
   
(* Get the png file in that directory and import it to a Graphics element. *)
jimsPicture = Import["jim.png"];

(* Define another graphics element, a plot of a sine function. *)
sinPlot = Plot[Sin[x], {x,0,2 Pi}, DisplayFunction->Identity];

(* And define a third graphics element, a raster image made from a random array of pixels.
   This one re-evaluates each time its invoked.  *)
graybox := Graphics[Raster[Table[Random[],{100},{100}]],AspectRatio->1];

(* Insert the PostScript code that displays a Mathematica Graphic into the Cell with the given tag.  
   This code is a combination of
     (a) the TurtleGraphics notebook, which generated GraphicsData in Postscript form with DisplayString, and
     (b) the TicTacToe notebook, which used CellTags to pick where to write the data.
*)
writeGraphics[theGraphics_, theCellTag_]:=Module[{nb},
	nb = SelectedNotebook[];							(* nb is the notebook that we're using. *)
	NotebookFind[nb,theCellTag,All,CellTags];			(* Select the cell whose tag is theCellTag. *)
	NotebookWrite[										(* Replace the contents of that cell with this stuff. *)
  		nb,
  		Cell[
  			GraphicsData["PostScript", DisplayString[theGraphics]],
  			CellTags->theCellTag
  			]
  		]
	];

the Buttons

Show Jim' s Picture  Show sin (x)  Show the random raster box

Scratch