且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

“使用 get 时出错"在 Matlab GUI 中使用“addlistener"函数

更新时间:2021-08-19 08:53:00

首先,您发布的代码并不是产生错误的代码.我猜测产生错误的代码如下所示:

First of all, the code that you posted isn't the code that is producing your error. I'm guessing that the code that yielded your error looked like this:

h = addlistener(hObject, 'Value', 'PostSet', @slider1_Callback);

在这种情况下,元属性作为第一个输入参数传递给 slider1_Callback,这会给您提供您所看到的即时错误.

In this instance, a meta property is passed as the first input argument to slider1_Callback which is giving you the immediate error you're seeing.

话虽如此,如果您想调用 slider1_Callback,您需要制作一个匿名函数,该函数实际上将正确的输入类型(和数量)传递给回调函数.这是一个这样做的.

That being said, if you want to call slider1_Callback you need to craft an anonymous function which actually passes the correct type (and number) of inputs to the callback function. Here is one which does that.

function slider1_CreateFcn(hObject, eventdata, handles)
    h = addlistener(hObject, 'Value', 'PostSet', ...
                    @(src,evnt)slider1_Callback(hObject, [], handles))
end

不过,更好的做法是使用单独的回调,而不是 GUIDE 为您创建的回调.这为您提供了更多的灵活性.此外,如果您只想显示值,则不需要所有其他输入,您实际上可以内联整个回调而不是单独的函数.

The better thing to do though, is to just use a separate callback rather then the one that GUIDE creates for you. This gives you a little bit more flexibility. Also, if you just want to display the value you don't need all of the other inputs and you can actually inline the entire callback rather than having a separate function.

h = addlistener(hObject, 'Value', 'PostSet', @(s,e)disp(get(hObject, 'Value')));

并在行动中展示它: