Pass Data between Gui`s

Hey Guys, I have created two GUI`s but i dont know how to pass Data between them. Both GUI`s are several m-files.
pls help me ....

 Accepted Answer

Max - there are probably several different ways to do this, so here is one. Let's assume that you have two GUIs named Gui1 and Gui2 and that they are distinct GUIs (i.e. you are not running two instances of the same one). In the Property Inspector for Gui1, set the HandleVisibility property to on, and the Tag property to Gui1. This will allow us to search for the GUI given its (unique) tag. Do the same for Gui2 (except name the tag Gui2). Save both.
Now suppose that in Gui2 you want access to some of the data in Gui1. What you require, is the handle to the latter. In a (say) push button callback of Gui2, you can add the following code
function pushbutton1_Callback(hObject, eventdata, handles)
% get the handle of Gui1
h = findobj('Tag','Gui1');
% if exists (not empty)
if ~isempty(h)
% get handles and other user-defined data associated to Gui1
g1data = guidata(h);
% maybe you want to set the text in Gui2 with that from Gui1
set(handles.text1,'String',get(g1data.edit1,'String'));
% maybe you want to get some data that was saved to the Gui1 app
x = getappdata(h,'x');
end
The above example tests out two ways in which we can get data from the other GUI - use either guidata which gives us the handles to all widgets of Gui1 AND any user-defined data that had been saved in Gui1 to the handles object as
function pushbutton3_Callback(hObject, eventdata, handles)
% in some Gui1 callback, we create the following xData field in the handles
% structure
handles.xData = -2*pi:0.0001:2*pi;
% now we save the data
guidata(hObject,handles);
We then access this data as shown previously.
The other way is to use the setappdata and getappdata pairings. Using the previous callback for Gui1, we can save the app data as
function pushbutton3_Callback(hObject, eventdata, handles)
% in some Gui1 callback, we create the following xData field in the handles
% structure
handles.xData = -2*pi:0.0001:2*pi;
% now we save the data
guidata(hObject,handles);
setappdata(handles.Gui1,'x',[1:53]);
and then retrieve it with getappdata.
NOTE how we use must use the handles.Gui1 to save/set the data. And that is it. Try the above and see what happens!

17 Comments

oh danke,danke,danke,danke..
Hi, I tried doing it the way it is depicted above but it doesnt work:( my goal is to transfer two input data from the GUI 'gui2' to the GUI 'testmenues'. I tried doing it with setappdata and getappdata since this was recommended when creating GUIs with GUIDE. 'gui2' is startet when the button 'untitled3' in the menu bar is pushed. THen input data shall be put in 'gui2' and transported to 'testmenues' as well as shown in this gui 'testmenues' in the respective edit textbox.
What do i do wrong? it doesnt work ...i guess i have serious problems with the handles somehow...i am not that fully understanding it yet.
I would be very glad for help since i havent found other really easy examples so far for this common procedure and this builds the basics of programming GUIs.
Best regards, John
John - since you want to pass data from gui2 to testmenues, you have to indicate the latter in the former. So in the pushbutton1_Callback of gui2 do the following
function pushbutton1_Callback(hObject, eventdata, handles)
hTestGui = findobj('Tag','testmenues');
val1 = str2double(get(handles.edit1,'String'));
val2 = str2double(get(handles.edit2,'String'));
if ~isempty(hTestGui)
% save the data to the other GUI
setappdata(hTestGui, 'val1', val1);
setappdata(hTestGui, 'val2', val2);
% update the result
handlesTestGui = guidata(hTestGui);
if isfield(handlesTestGui,'result')
set(handlesTestGui.result,'String',num2str(val1+val2));
end
end
close
Note how we access testmenues through its tag property and set the val fields through the calls to setappdata. We then use guidata to get handles to the UI controls of testmenues so that we can update result with the sum of the two inputs. Note that I had to remove the code from the result_Callback of testmenues since it was referencing a handle that did not exist (i.e. gui2).
John
John on 9 Sep 2015
Edited: John on 9 Sep 2015
Dear Geoff, thank you very much for your Help!!
It works fine! i think i make a bit progress on the understanding of handles to the figure and data. So handles are actually structs that save either GUI Objects (like axis, figure, etc) or other data given from the user right?
I saw another possibility of getting the handle for the main GUI. You suggested:
hTestGui = findobj('Tag','testmenues');
so this command searches for every figure that has the tag testmenues right? theoretically there could be more who have it.
Instead i saw another option.
function testmenues_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to testmenues (see VARARGIN)
% Choose default command line output for testmenues
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
setappdata(0,'hMainGui',gcf) % set handle to current figure and name this handle 'hMainGui', better then using gcf later because figures may change
% this is the handle to the Parent figure.
By adding the line
setappdata(0,'hMainGui',gcf)
to the testmenues_openingFcn one has access to this figure from every other GUI right?
So modifying the callback to:
function pushbutton1_Callback(hObject, eventdata, handles)
%hTestGui = findobj('Tag','testmenues') %Zweite Moeglichkeit der
%Handeluebergabe
hTestGui = getappdata(0, 'hMainGui') % Pick the Variable 'hMainGui' from the Root. hMainGui is a handle to the GUI 'Try1'
val1 = str2double(get(handles.edit1,'String'))
val2 = str2double(get(handles.edit2,'String'))
if ~isempty(hTestGui)
% save the data to the other GUI
setappdata(hTestGui, 'val1', val1);
setappdata(hTestGui, 'val2', val2);
% update the result
handlesTestGui = guidata(hTestGui);
if isfield(handlesTestGui,'result')
set(handlesTestGui.result,'String',num2str(val1+val2));
end
end
close
solves the issue too. Thank you so much for your help once again! Best regards, John
John
John on 11 Sep 2015
Hey , I would really like to confirm my understanding of handles and the procedure with setappdata and getappdata plz.
1) So basically this method is chosen in order to not waste the working space and to get confused with globally defined and similar, or even same named variables right?
2) Handles are always related to a GUI object right? they are structs and contain graphic characteristics of the GUI object (e.g. axes, figure, pushbutton etc) and can also contain information given by the user like variables.
3) By using setappdata and getappdata the handles are not transfered from one GUI to another! they remain the same for every GUI. It is just achieved that the other GUI, lets say GUI1 now has access to read a specific content of GUI2, specified by the name (e.g. 'variable1', 'axis', 'pushbotton' etc.). Is that correct?
I would appreciate an answer so that i can be sure to have understood the most important part somehow!
Thank you very much and best regards, John
John - from setappdata, Use this function to store data in a UI. You can retrieve the data elsewhere in your code using the getappdata function. Both of these functions provide a convenient way to share data between callbacks or between separate UIs. Using these functions are preferred over polluting the workspace with variables.
When creating a GUI through GUIDE, a handles structure is passed to each callback within the GUI. This structure, by default, has fields giving the graphics object handle for each UI element of your GUI. You can also use this structure to manage user-defined data so that data obtained from one callback can be shared within another callback of the same GUI. See guidata for details.
The handles are not transferred from one GUI to another using setappdata or getappdata. You can just use the getappdata to get certain data that has been stored in the UI, or use guidata to get the handles to the other GUI.
John
John on 14 Sep 2015
Thank you!!!
I'm going to do the same thing but it doesn't work for me, I'm very confused; PLEASE HELP me out.
This is my code (short version):
m file:
function varargout = GUI_1(varargin)
...
function Untitled_1_Callback(hObject, eventdata, handles)
% hObject handle to Untitled_1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
prompt = {'Maximum ambient temperature:'};
title = 'General Inputs';
lines = 1;
def = {''};
options.Resize='on';
options.WindowStyle='normal';
options.Interpreter='tex';
answer=str2double(inputdlg(prompt,title,lines,def,options));
handles.Ta = answer(1);
guidata(hObject,handles)
...
GUI_2 m file:
function varargout = GUI_2(varargin)
...
A=1/Ta;
...
after running, I get this error because I can't pass data from GUI_1 to GUI_2 :
??? Undefined function or variable 'Ta'.
Error in ==> GUI_2>Calculate_Callback at 401
A=1/Ta;
Error in ==> gui_mainfcn at 96
feval(varargin{:});
Error in ==> GUI_2 at 42
gui_mainfcn(gui_State, varargin{:});
Error in ==> @(hObject,eventdata)GUI_2('Calculate_Callback',hObject,eventdata,guidata(hObject))
??? Error while evaluating uicontrol Callback
Hamid - in the second GUI, you have to implement one of the two methods (to pass data between GUIs) as discussed in the answer. Have you tried one of them?
yes man but don't work.
can you please write the correct code that I should do.
I'm 3 days working in this code and getting crazy.
In the callback function of GUI2 that makes use of TA, do the following
TA = [];
% get the handle of Gui1
h = findobj('Tag','Gui1');
% if exists (not empty)
if ~isempty(h)
% get handles and other user-defined data associated to Gui1
g1data = guidata(h);
if isfield(g1data,'TA')
TA = g1data.TA;
end
end
if ~isempty(TA)
A=1/Ta;
% etc.
end
The above assumes that your first GUI has been named or tagged as Gui1 and its HandleVisibility property is set to on.
I set a couple of breakpoints and h is empty 0*1 double and Ta is empty 0*0 double.
What's wrong?
thank you Geoff, you are the best.
Hamid - please stop posting duplicate questions or commenting on other questions in order to maximize your chance of getting an answer. As http://www.mathworks.com/matlabcentral/answers/258914-error-passing-data-from-gui-1-to-gui-2 is your latest question, then I will assume that the dialog here has come to an end.
Geoff,
I used this code of yours.The first time it worked flawlessly.(Thank You!) The second time I used it in two other guis, I did not get any error, nor did the data get transferred. Any suggestions on what I could do? I have changed the handle visibility f both to on and changed their tags to their respective names as well.
function pushbutton1_Callback(hObject, eventdata, handles) % get the handle of Gui1
h = findobj('Tag','Gui1'); % if exists (not empty)
if ~isempty(h) % get handles and other user-defined data associated to Gui1
g1data = guidata(h); % maybe you want to set the text in Gui2 with that from Gui1
set(handles.text1,'String',get(g1data.edit1,'String')); % maybe you want to get some data that was saved to the Gui1 app
x = getappdata(h,'x');
end
This is what i am seeing in the console window. Opening_Page
File_Name =
th.gif
Path_Name =
C:\Users\deepa\SkyDrive\Documents\Project Lab\
Hi, Geoff and thanks for your thoughts. I have made my code depeding on your explaination and I have a problem. What I want is to run the 1st gui then save its output with is a matrix with 1369 rows and different columns. The saving of the output in the first gui takes place with the following pushbutton:
fid = fopen([pathname,filename,'_result.dat'],'w');
fprintf(fid,[intinfotext,tauinfotext]);
fprintf(fid,frmtext,datatosave');
fclose(fid);
Afterwards, I need to extract the saved data into another the second gui in a list box, then to run the second gui. But by runing my code with your idea of
g1data = guidata(h)
set(handles.edit_tauexp,'string',x(:,1));
set(handles.edit_rexp,'string',x(:,2));
g1data shows me too many things and an error message:
Index exceeds matrix dimensions.
Error in gui3>pushbutton8_Callback (line 362)
set(handles.edit_tauexp,'string',x(:,1));
Would you please help me for that?
Ahmed - what can you tell us about x? What are the dimensions? Put a breakpoint at this line of code and then use the debugger to see what is going wrong.

Sign in to comment.

More Answers (3)

Sara
Sara on 4 Aug 2014
In GUI_1, store everything you need to share in handles, and call GUI_2 as:
GUI_2(handles)
This may go into a pushbutton callback, i.e. where you want to have GUI_2 appear. In the opening function of GUI_2, you variables will be in varargin{1}.you_var_name. You can now do (in GUI_2 opening function):
handles.myvar1 = varargin{1}.myvar1
to carry around variables from GUI_1 in GUI_2. You could also
The same works from GUI_2 to GUI_1.

4 Comments

Thanks for your perfect answer
Thank you very much! I was looking for this answer for half a day.
This is also covered in the FAQ.
Sharing between multiple GUIs. If the "main" GUI calls other GUIs, then the best way to do it is by passing variables in via the input argument list, and accepting output variables via the output argument list. The output argument of GUI2 can then be sent into GUI3. So someplace in GUI1 (like the callback function of the "Go!" button of GUI1), you'd have this
[out2a out2b out2c] = gui2(in2a, in2b, in2c, in2d);
[out3a out3b] = gui3(out2a, out2b);
or something along those lines. The arguments can be extracted out of the varargin cell array of your opening code for the GUI, for example in the GUI's "OpeningFcn" function if you used GUIDE. Once they are in your opening function, then they can be shared amongst the other functions in the GUI with the methods mentioned earlier in this section. This method will not let GUI1 control GUI2 and GUI3's parameters "live" - they can be changed only when calling the GUIs. To have GUI1 control GUI2 when GUI2 is already running, you can use the assignin() function.
This answer from Geoff Hayes in the Answers forum may also help you in the multiple GUI situation: [3]
Some advice regarding Sara's answer is to use another name for the handle in the second GUI. Call it handles2 or something, not handles
handles2 = varargin{1};
or you may not be able to control the controls in the second GUI because the handles in the first/calling GUI will have been overwritten by this new/incoming handles. For example, if you don't, handles.button1 may refer to the other/called gui's button1, not the gui in this gui's, the calling gui's, button1.

Sign in to comment.

Categories

Find more on Interactive Control and Callbacks in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!