Trouble saving a variable to a base GUI and accessing it in another.

1 view (last 30 days)
I have 3 GUIs:
  1. Gui1 is the base window.
  2. Gui2 is a callback from a button in Gui1, gets user input, then attempts to save the input as a variable in Gui1.
  3. Gui3 is a callback from a button in Gui1 and uses the data saved from Gui2.
Below are outlines of the code I have.
:
function GUI1
% create figure
fig = figure(<figure settings>,'tag','Main Window');
% figure handles
mainWindow = guihandles(fig);
% create an empty variable
mainWindow.data = [];
% create two buttons, button2 and button3 to call Gui2 and Gui3, respectively\
% set their callbacks accordingly
set(mainWindow.button2,'callback',{@Gui2,mainWindow});
set(mainWindow.button3,'callback',{@Gui3,mainWindow});
% save the handle
guidata(fig,mainWindow);
end
Gui2:
function Gui2
% code gets user input in a variable userInput
% find object from tag
saveFig = findobj('tag','Main Window');
% get the handles of Gui1's figure
target = guidata(saveFig);
% set the data
target.data = userInput;
% save handle
guidata(saveFig,target);
end
I'm running Gui1 first, then Gui2 to get the data and save it into Gui1. After that, I'm trying to pass the saved variable from Gui1 into Gui3, but somewhere along the way it appears Gui2 failed to pass the variable into Gui1, so the "data" field is still showing as [].
Any tips? I'm really not sure where I'm going wrong here.
EDIT: I just figured it out, the issue was that I was trying to recall data in Gui3 by directly accessing the handles from the callback setting in the main window, which meant that the updated mainWindow handles weren't being accessed. I changed it so whenever I need the stored variables I would use findobj and guidata to obtain the updated mainWindow handles.

Accepted Answer

Image Analyst
Image Analyst on 28 Sep 2015
Pass data back to the main routine
function data = Gui2
% Code.
% Now, call gui2 in main program:
data = Gui2() % Get data back out
mainWindow.data = data; % Assign data to handles structure in main program.
  2 Comments
TastyPastry
TastyPastry on 28 Sep 2015
Does the second block of code replace
mainWindow.data = [];
If so, wouldn't this cause Matlab to error since there isn't a pause/wait which allows Gui2 to complete before assigning the variable data back?
Image Analyst
Image Analyst on 28 Sep 2015
You don't need that line at all.
You can have the code wait for the second GUI to finish and close before continuing on with the parent, calling GUI.

Sign in to comment.

More Answers (0)

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!