我一直在尝试编程一个GUI,它应该接收一个变量作为输入并执行几个生成另一个变量的操作。 GUI将有一个关闭GUI的按钮。
我不是(也不想)使用GUIDE。
下面,我提供了一个GUI的最小工作示例,只需在输入变量中添加一个。 “完成”按钮关闭GUI但我找不到将变量导出到工作区的方法。
% Is this the correct way to initialize the function for what I am trying to do?
function outputVariable = exampleGUI(inputVariable)
% Initialize main figure
hdl.mainfig = figure();
% 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(~, ~, ~)
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 done(~, ~, ~)
delete(hdl.mainfig); % close GUI
end
end
我想做点什么:
在工作区中:
outputVariable = exampleGUI(inputVariable)
在输入变量中添加一个输入变量一次后,我会按下“完成”按钮,GUI将关闭,工作空间将同时包含inputVariable和outputVariable。
非常感谢。
fnery
答案 0 :(得分:2)
这是你可以做的一个例子。你可以做很多事情来使用你想要的功能。通常我不希望除了输入和输出以及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