MATLAB中为控件(uicontrol)绑定Callback函数,回调函数

笔者走了许多弯路,终于找到这个方法,分享给大家。

'callback',@(~,~)colormapeditor(h)

如果版本老不支持“~”这种写法,那就改成:

'callback',@(x,y)colormapeditor(h)

比如,在一个控件的回调函数中生成其他控件,并为生成的控件绑定回调函数:

1 function fun_threshold_Callback(hObject, eventdata, handles)
2 % hObject handle to fun_threshold (see GCBO)
3 % eventdata reserved - to be defined in a future version of MATLAB
4 % handles structure with handles and user data (see GUIDATA)
5 ...
6 Hnd2=uicontrol(gcf,'Style','pushbutton','String','确定','Position',[260 20 30 25]); % gcf可以省略
7 set(Hnd2,'Callback', @(x,y)fun_adaptiveThreshold(handles)); % 使用句柄调用回调函数
8 ...

下面为Hnd2要调用的调用函数:

1 function fun_adaptiveThreshold(handles)
2 % 回调函数体 
3 ...

其他知识:

1.uicontrol(Hnd1); % 文本框获得焦点

2.guidata(hObject, handles); % 更新句柄

3.在主程序面板上点击按钮关闭其他所有创建的窗口:

setappdata(gcf, 'IgnoreCloseAll', 1); % 防止主程序窗口被关闭

close all; % 关闭其他操作产生的窗口

....

(未完待续)