Labfans是一个针对大学生、工程师和科研工作者的技术社区。 | 论坛首页 | 联系我们(Contact Us) |
![]() |
![]() |
#1 |
高级会员
注册日期: 2019-11-21
帖子: 3,006
声望力: 66 ![]() |
![]()
是否可以从函数内部编写GUI?
问题在于,所有GUI功能的回调都在全局工作空间中进行评估。但是函数具有其自己的工作空间,并且无法访问全局工作空间中的变量。是否可以使GUI功能使用功能的工作区?例如: function myvar = myfunc() myvar = true; h_fig = figure; % create a useless button uicontrol( h_fig, 'style', 'pushbutton', ... 'string', 'clickme', ... 'callback', 'myvar = false' ); % wait for the button to be pressed while myvar pause( 0.2 ); end close( h_fig ); disp( 'this will never be displayed' ); end 此事件循环将无限期运行,因为回调不会修改myvar中的myvar 。相反,它将在全局工作区中创建一个新的myvar 。 回答: 有多种构建GUI的方法 ,例如使用App Designer,GUIDE或以编程方式创建它(我将在下面说明此选项)。注意为GUI组件定义回调函数的不同方法以及在组件之间共享数据的可用选项也很重要。 我偏爱的方法是使用嵌套函数作为回调。这里以一个简单的GUI为例: function make_useless_button() % Initialize variables and graphics: iCounter = 0; hFigure = figure; hButton = uicontrol('Style', 'pushbutton', 'Parent', hFigure, ... 'String', 'Blah', 'Callback', @increment); % Nested callback function: function increment(~, ~) iCounter = iCounter+1; disp(iCounter); end end 运行此代码时,每次按下按钮时,显示的计数器应增加一,因为嵌套函数的increment可以访问make_useless_button的工作区,因此可以修改iCounter 。请注意,按钮回调设置为increment的函数句柄 ,并且该函数默认情况下必须接受两个参数:触发回调的UI组件的图形句柄以及关联事件数据的结构。在这种情况下,我们不使用~来忽略它们,因为我们没有使用它们。 将上述方法扩展到您的特定问题,您可以添加循环并更改回调,以便将flag变量设置为false: function make_stop_button() % Initialize variables and graphics: keepLooping = true; hFigure = figure; hButton = uicontrol('Style', 'pushbutton', 'Parent', hFigure, ... 'String', 'Stop', 'Callback', @stop_fcn); % Keep looping until the button is pressed: while keepLooping, drawnow; end % Delete the figure: delete(hFigure); % Nested callback function: function stop_fcn(~, ~) keepLooping = false; end end 这里需要使用drawnow ,以使按钮回调有机会中断循环中的程序流并修改keepLooping的值。 |
![]() |
![]() |