User interface MATLAB图形用户界面中for循环的中断

User interface MATLAB图形用户界面中for循环的中断,user-interface,matlab,User Interface,Matlab,我在MATLAB中GUI的打开函数中有一个for循环,我试图使用一个回调按钮来打破这个循环。我对MATLAB是新手。以下是我的代码: %In the opening function of the GUI handles.stop_now = 0; for i=1:inf if handles.stop_now==1 break; end end % Executes on button press function pushbutton_Callback(hObj

我在MATLAB中GUI的打开函数中有一个
for
循环,我试图使用一个回调按钮来打破这个循环。我对MATLAB是新手。以下是我的代码:

%In the opening function of the GUI
handles.stop_now = 0;
for i=1:inf
   if handles.stop_now==1
      break;
   end
end


% Executes on button press 
function pushbutton_Callback(hObject, eventdata, handles)
% hObject    handle to end_segmenting_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.stop_now=1;
guidata(hObject, handles);

出于某种原因,尽管定义了带有句柄的变量,但按下按钮时循环不会中断。有人知道发生了什么吗?谢谢。

我发现这里有两个潜在的问题

第一:变量
handles
不是引用,设置
handles.stop\u now=1将“丢失”
按钮\u回调
。使用或来存储和检索数据

使用函数。请参阅以获得更好的解释


简介:MatlabGraphics是Java Swing和IO操作(如按下按钮)在一个特殊的线程-事件调度线程(EDT)上进行的。调用drawnow();刷新事件队列并更新图形窗口。

您遇到的问题是,传递给for
句柄的值的结构在调用opening函数时是固定的。您永远无法检索由
按钮\u回调更新的新结构。您可以通过调用循环来检索新结构。以下是我建议您尝试编写循环的方式:

handles.stop_now = 0;  %# Create stop_now in the handles structure
guidata(hObject,handles);  %# Update the GUI data
while ~(handles.stop_now)
  drawnow;  %# Give the button callback a chance to interrupt the opening function
  handles = guidata(hObject);  %# Get the newest GUI data
end
更大的GUI设计问题。。。 根据您的评论中关于您试图用GUI实现什么的附加描述,我认为可能有更好的方法来设计它。您可以取消循环和停止按钮,并在GUI中添加“添加ROI”按钮,而不是让用户重复输入ROI的连续循环,然后用户必须按下按钮才能停止ROI。这样,当用户想要添加另一个ROI时,只需按下一个按钮。您可以首先使用以下初始化替换打开函数中的for循环:

handles.nROIs = 0;  %# Current number of ROIs
handles.H = {};  %# ROI handles
handles.P = {};  %# ROI masks
guidata(hObject,handles);  %# Update the GUI data
然后,您可以将按钮的回调替换为以下内容:

function pushbutton_Callback(hObject,eventdata,handles)
%# Callback for "Add new ROI" button
  nROIs = handles.nROIs+1;  %# Increment the number of ROIs
  hROI = imfreehand;  %# Add a new free-hand ROI
  position = wait(hROI);  %# Wait until the user is done with the ROI
  handles.nROIs = nROIs;  %# Update the number of ROIs
  handles.H{nROIs} = hROI;  %# Save the ROI handle
  handles.P{nROIs} = hROI.createMask;  %# Save the ROI mask
  guidata(hObject,handles);  %# Update the GUI data
end

我使用的是GUI数据,我已经检查过确保handles.stop\u现在在按钮\u回调之外更新(即,我知道它没有丢失),但由于某种原因,它在for循环中无法识别……我明白了,所以关键是在循环中调用GUI数据。我现在实际上遇到了另一个问题。我使用for循环从带有imagefreehand的图像中捕获ROI。对于i=1:inf drawnow handles=guidata(hObject);if handles.stop_now==1 break;端点句柄.H{i}=imfreehand;handles.P{i}=handles.H{i}.createMask;问题是,一旦我按下按钮,我只能在选择了一个额外的徒手区域后退出循环。我怎样才能绕过它呢?在您的实现中,
break
退出循环,控制流转到
imfreehand()
。因此,您应该使用
return
而不是
break
。谢谢您的帮助。问题是,我用这个程序来分割生物图像。在一张图像中,我可能需要分割多达20个不同的对象,因此我不希望用户每次需要添加额外的ROI时都按下按钮。我只是想知道是否有任何方法可以解决我目前的设置问题。