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

查看:233
本文介绍了从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是脚本并且在bar.m文件中定义了bar,则

可以正常工作.在我看来,回调函数在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)

推荐答案

对于定义回调,我发现最可靠的方法是使用

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 < handle)

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天全站免登陆