如何在MATLAB中创建动态回调函数?

5

我有这一行代码:

delete_btn = uicontrol(rr_ops, 'Style', 'pushbutton', 'String', 'Delete Graphic', 'Position', [13 135 98 20], ...
'Callback', 'delete_graphic');

并且在这个函数的稍上方:

function delete_graphic
global rr_list
selected = get(rr_list, 'Value');
selected
return;

为什么这段代码不起作用?我真的不理解...
我需要什么?我创建了一个按钮和一个列表框,点击按钮 - 从列表框中删除选择的元素。
谢谢帮助。
附言 总是出现这个错误:
??? Undefined function or variable 'delete_graphic'.
??? Error while evaluating uicontrol Callback

这是所有我的代码:http://paste.ubuntu.com/540094/ (第185行)

1个回答

10
定义回调函数的通常首选方法是使用函数句柄而不是字符串。当您使用字符串时,字符串中的代码会在基础工作区中进行评估。这意味着,在评估回调时,字符串中使用的所有变量和函数都必须存在于基本工作区中。这会导致GUI设计不良,因为您不希望您的GUI操作依赖于基础工作区(用户可以轻易修改,从而可能破坏GUI)。
这也解释了您遇到的错误。函数delete_graphic在文件rr_intervals.m中被定义为子函数。子函数只能由在同一m文件中定义的其他函数调用,因此delete_graphic在基础工作区中不可见(在其中评估您的字符串回调)。使用函数句柄回调是更好的选择。以下是如何做到这一点:
  • Change the callback of your button (line 216) from 'delete_graphic' to @delete_graphic.
  • Change the function definition of delete_graphic (line 185) to:

    function delete_graphic(hObject,eventdata)
    

    where hObject is the handle of the object issuing the callback and eventdata is optional data provided when the callback is issued.

编辑:

如果你想向 delete_graphic 函数传递其他参数,可以执行以下步骤:

  • Add the additional input arguments to the end of the function definition. For example:

    function delete_graphic(hObject,eventdata,argA,argB)
    
  • Use a cell array when you set the callback for your button, where the first cell contains the function handle and the subsequent cells each contain an input argument. For example:

    set(delete_btn,'Callback',{@delete_graphic,A,B});
    

    There is one caveat to this, which is that the values A and B stored in the cell array are fixed at what they are when you set the callback. If you change A or B in your code it will not change the values stored in the cell-array callback.

如果您无法使用上述解决方案(即如果AB需要更改值),则还有其他几种选项可以在GUI的回调之间共享数据

  • 你可以重新组织代码,利用嵌套函数。这使得在回调之间共享数据变得非常容易。一些使用嵌套函数创建GUI的好例子可以在MathWorks文件交换提交使用嵌套函数的GUI示例中找到,作者是Steven Lord
  • 你可以将数据存储在一个uicontrol对象的UserData属性中。要访问或更新它,只需要对象句柄。
  • 你可以使用SETAPPDATA/GETAPPDATA函数将数据附加到句柄图形对象(即uicontrol)上。
  • 由于你的代码似乎是使用GUIDE创建的,所以你可以使用GUIDE创建的handles结构来使用GUIDATA函数存储数据。

谢谢。它起作用了,但是我如何将其他参数传递给delete_graphic函数? - AndrewShmig
@Andrew:我在我的答案中添加了更多细节,解释了如何将其他参数传递给您的函数。 - gnovice

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接