MATLAB GUI手记——用户菜单以及回调函数的语法规则

http://bilibili.com/video/BV1Ya4y1t7rZ?from=search&seid=18404440388539513689

学习要点:

  • 定义回调函数的语法规则。

创建图形用户界面有4种方式:

  1. 纯m语言创建。
  2. 命令方式(在命令行窗口敲入命令:figure);
  3. 通过guide命令创建(在命令行窗口敲入命令:guide);
  4. 通过appdesigner命令创建(在命令行窗口敲入命令:appdesigner);

其中,方法4是比较新的方法。目前matlab停止了guide的更新,以后会推广方法4(2016及以上版本具备).

 下面用纯m语言创建图形用户界面:

代码:

%%菜单设计
h_figure=figure;
set(h_figure,'menubar','figure');

运行结果:

 

 

 代码:

%%菜单设计
h_figure=figure;
set(h_figure,'menubar','none');

运行结果:

 

 带GUI的代码,也是可以调试运行的,在想调试的地方设置断点即可。

 

 

 

注解:

  1. 参数obj是二级菜单blue的句柄。

gui_lianxi.m

%----------------------------%
%matlab GUI设计的练习代码
%2021/2/12
%----------------------------%

%%菜单设计
h_figure=figure;
%set(h_figure,'menubar','figure');
set(h_figure,'menubar','none');
text_y='这是黄色';
text_w='这是白色';
%%用户菜单的建立
h_menu=uimenu(h_figure,'label','&color');
h_submenu1=uimenu(h_menu,'label','&green','Callback','set(gcf,''color'',''green'')'); %这个是直接把回调函数的内容写在这里,适合只有1行代码的回调函数,最不推荐这种回调函数的写法
h_submenu2=uimenu(h_menu,'label','&red');
h_submenu3=uimenu(h_menu,'label','&blue');
h_submenu4=uimenu(h_menu,'label','&yellow');
h_submenu5=uimenu(h_menu,'label','&white');
set(h_submenu2,'Callback','set_color');  % 'Callback'代表回调函数,set_color就是要定义的回调函数(set_color.m),
set(h_submenu3,'Callback',@set_color_1); % 这种回调函数set_color_1.m需要有参数obj,event
set(h_submenu4,'Callback',{@set_color_2,text_y});% 这种回调函数set_color_2.m 需要向回调函数传入一些参数
set(h_submenu5,'Callback',{'set_color_3',text_w});

 

set(h_submenu4,'Callback',{@set_color_2,text_y});% 这种回调函数set_color_2.m 需要向回调函数传入一些参数

注解:

这样的回调函数最常用,传递一个函数,函数中传入一些参数。

 

set_color.m文件:

function set_color()
    set(gcf,'color','red');
end

 set_color_1.m文件:

function set_color(obj,event)  
    set(gcf,'color','blue');   
end

 set_color_2.m文件:

function set_color(~,~,text_y)  
    set(gcf,'color','yellow');   
    msgbox(text_y);
end

 set_color_3.m文件:

function set_color(~,~,text_w)  
    set(gcf,'color','white');   
    msgbox(text_w);
end

 

posted on 2021-02-12 11:51  一杯明月  阅读(1237)  评论(0编辑  收藏  举报