我有2个按钮。如果我按下一个无限循环将运行,如果我按其他循环必须中断。请一些代码帮助。
提前致谢
答案 0 :(得分:2)
您使用的是GUIDE还是"编程" GUI?以下是程序化gui的一个小例子;类似的概念可能适用于GUIDE。 (我个人喜欢程序化gui路线增加的灵活性,而且我总是不可挽回地打破我创建的任何GUIDE gui ...)
无论如何,在这个例子中需要注意几点:
"无限"中的暂停声明需要循环以便处理来自cb_button2的中断。从Matlab help:"如果正在执行其回调的对象的可中断属性,则可以中断回调。但是,只有当它或它触发的函数调用drawow,figure,getframe,pause或waitfor时才会被中断。"
function my_gui(varargin)
mainfig = figure;
out.h_button1 = uicontrol(mainfig,...
'Style','pushbutton',...
'Units','Normalized',...
'Position',[0,0.5,1,0.5],...
'String','Button 1',...
'Callback',@cb_button1);
out.h_button2 = uicontrol(mainfig,...
'Style','pushbutton',...
'Units','Normalized',...
'Position',[0,0,1,0.5],...
'String','Button 2',...
'Callback',@cb_button2);
out.button2_flag = 0; %flag indicating whether button 2 has been pressed yet
set(mainfig,'UserData',out);%store "global" data in mainfig's UserData (for use by callbacks)
function cb_button1(varargin)
out = get(gcbf,'UserData'); %gcbf: handle of calling object's figure
while ~out.button2_flag
disp('Aaaahhh, infinite loop! Quick press Button 2!');
out = get(gcbf,'UserData'); %reload "global" data
pause(0.1); %need this so this callback may be interrupted by cb_button2
end
disp('Thanks! I thought that would never end!');
function cb_button2(varargin)
out = get(gcbf,'UserData'); %gcbf: handle of calling object's figure
out.button2_flag = 1;
set(gcbf,'UserData',out); %save changes to "global" data