从 GUI 访问嵌套函数 [英] accessing nested functions from GUI

查看:13
本文介绍了从 GUI 访问嵌套函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用几乎多合一的函数,在主函数和嵌套函数中创建 GUI 和必要的变量以用作回调操作.

I'm trying to have almost all-in-one function that creates GUI and necessary variables in main function and nested functions to be used as callback actions.

当我有

function[]=foo()
A=1;

uicontrol('style','pushbutton','callback','A=bar(A);')

function[OUT]=bar(IN)
OUT=IN+1;

出现错误:

Undefined function 'bar' for input arguments of type 'double'.

Error while evaluating uicontrol Callback`

如果 foo 是一个脚本并且 barbar.m 文件中定义,它就可以工作.在我看来,回调在 MATLAB 工作区中的默认变量和当前工作目录中的脚本/函数中使用.如何访问调用函数中定义的变量(此处为变量 A)和嵌套在调用函数中的函数(此处为函数 bar)

if foo is a script and bar is defined in bar.m file it works. It seems to me that callbacks use in default variables in MATLAB workspace and scripts/fuctions in current working directory. How can I access variables defined IN the calling function (here the variable A) and functions nested in the calling function (here the function bar)

推荐答案

对于定义回调,我发现最可靠的方法是使用 匿名函数.也就是说,如果 barfoo 的嵌套函数,那么它已经可以访问 A 并且可以修改 A.

For defining callbacks, I have found the most reliable approach to be using anonymous functions. That being said, if bar is a nested function of foo, then it already has access to A and can modify A.

function = foo()
    A = 1;

    uicontrol('style', 'pushbutton', 'callback', @(s,e)bar())

    % This is a nested function that already has access to A
    function bar()
        A = A + 1;
    end

    % Let's call bar here to demonstrate it updates A
    bar();
    disp(A);
end

此外,您的回调实际上不能将输出传递回它们作为回调的控件的工作区.如果你想返回一个结果,你要么想要 1) 将结果存储在图形对象的 UserData 中,2) 使用我们展示的嵌套子函数,或者 3) 将一个自定义句柄对象的句柄传递给回调(classdef object )

Also, your callbacks can't actually pass outputs back to the workspace of the control for which they are the callback. If you want to return a result you would either want to 1) store the result in the UserData of the graphics object, 2) use a nested subfunction as we've shown, or 3) pass a handle to a custom handle object to the callback (classdef object < handle)

这篇关于从 GUI 访问嵌套函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆