这是你可以做的一个例子。你可以做很多事情来使用你想要的功能。通常我不喜欢在输入和输出以及guihandles之外的整个函数工作区中有任何变量。我使用setappdata和getappdata来存储其他变量并使它们可以被回调访问。这取决于您,但以下是如何使您的简单gui工作的示例。 CloseRequestFcn允许您处理用户刚关闭gui时发生的情况。希望这可以帮助。此外,waitfor会阻止函数返回,直到函数关闭。如果需要,您还可以将数字的'WindowStyle'属性设置为'modal',以强制用户在关闭gui之前输入输入。

function outputVariable = exampleGUI(inputVariable)

% Any variables declared here will be accessible to the callbacks

% Initialize output

outputVariable = [];

% Initialize newVariable

newVariable = [];

% Initialize main figure

hdl.mainfig = figure('CloseRequestFcn',@closefunction);

% Add Button

hdl.addPushButton = uicontrol(hdl.mainfig, 'Units', 'normalized', 'Position',[0.05 0.6 0.3 0.25], 'String', 'Add One', 'Callback', @addOne);

% Done Button

hdl.donePushButton = uicontrol(hdl.mainfig, 'Units', 'normalized', 'Position',[0.65 0.6 0.3 0.25], 'String', 'Done', 'Callback', @done);

% Static text

hdl.sliceNoText = uicontrol(hdl.mainfig,'Style','text','Fontsize',16,'Units','normalized','Position',[0.35 0.2 0.3 0.25]);

function addOne(hObject,eventdata)

inputVariable = inputVariable+1; % add one to the current inputVariable

set(hdl.sliceNoText, 'String', num2str(inputVariable)); % change static text

newVariable = inputVariable; % new variable to be exported

end

function closefunction(hObject,eventdata)

% This callback is executed if the user closes the gui

% Assign Output

outputVariable = newVariable;

% Close figure

delete(hdl.mainfig); % close GUI

end

function done(hObject,eventdata)

% Assign Output

outputVariable = newVariable;

% Close figure

delete(hdl.mainfig); % close GUI

end

% Pause until figure is closed ---------------------------------------%

waitfor(hdl.mainfig);

end

更多推荐