0

I'm getting this error:

Error in ==> APP>pushbutton2_Callback at 109
img=imread(FileName)

When I try to use FileName in pushbutton2_Callback I'm getting the error mentioned

FileName is variable in pushbutton1_Callback.

2 Answers 2

4

You need to pass the variable FileName from one callback to the other. To do this, you can assign the variable to the 'UserData' field of pushbutton1. Your code under pushbutton1_Callback should look something like:

FileName=uigetfile();
set(handles.pushbutton1,'UserData',FileName);

Next, you need to read in the variable under your pushbutton2_Callback:

FileName=get(handles.pushbutton1,'UserData');
img=imread(FileName);

If you want to check your results, you can always leave the semicolons off the end of the lines.

1

There's a general method to store data with your gui for use between callbacks. You can add arbitrary fields to the handles object, so you can put in your pushbutton1 callback

handles.filename = FileName;
guidata(hObject,handles); 

The second line is boilerplate code that you need to put at the end of any callback that changes values in the handles structure.

Now all of your callbacks will have access to the file name. In your specific case, in callback 2, you would have

img = imread(handles.filename);

Of course, you might want to use this image later on in another function, so you can store it in handles too

handles.img = img;
guidata(hObject, handles);
2
  • You can do effectively the same thing with setappdata and getappdata without having to remember the guidata bit.
    – Adrian
    May 28, 2010 at 14:43
  • But then you have to know the figure handle, right? I guess you could call gcf, but then you'd run into a problem if the user maximized another window before your callback executed. I prefer the dot reference notation anyway.
    – Marc
    May 29, 2010 at 4:16

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.