本文介绍了使用uigetdir作为按钮的回调,由于奇怪的无效参数而导致崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Matlab(R2016a)GUI上创建一个简单的浏览"按钮.我的代码是这样的:

I am trying to create a simple "browse" button on a Matlab (R2016a) GUI.My code is something like:

hd = dialog;
hb = uicontrol('parent',hd,'style','pushbutton','string','browse',...
'callback',@uigetdir);

回调函数uigetdir具有2个可选参数STARTPATH, TITLE.原则上,我可以通过将它们与单元格数组上的函数句柄(例如

The callback function uigetdir has 2 optional arguments STARTPATH, TITLE. In principle I could pass these on my callback by concatenating them with the function handle on a cell array, such as

hd = dialog;
hb = uicontrol('parent',hd,'style','pushbutton','string','browse',...
'callback',{@uigetdir,'myStartPath','myTitle');

无论我的浏览按钮调用带有或不带有可选参数的uigetdir,它都会崩溃.错误不同,原因相同:uicontrol决定将2个不可调用的怪异变量(包含UI属性)作为回调函数的参数,并且uigetdir不知道如何处理它们.

Whether my browse button calls uigetdir with or without the optional arguments, it will crash. Different errors, same reason: uicontrol decides to include 2 uncalled-for, weird variables (containing UI properties) as arguments to the callback function, and uigetdir doesn't know what to do with them.

这是否意味着我不能在GUI中将uigetdir(或几乎任何其他内置函数)用作回调函数?除了编写自定义函数外,还必须有解决方案吗?

Does this mean I cannot use uigetdir (or pretty much any other built in function) as a callback function in a GUI? There must be a solution besides writing a custom function, no?

推荐答案

默认情况下,所有uicontrol对象都传递两个输入参数:

By default all uicontrol objects are passed two input arguments:

  • uicontrol自身处理
  • 一个对象,其中包含特定于事件的信息.
  • The uicontrol handle itself
  • An object containing information specific to the event.

通过在函数名称后附加@来创建函数句柄来定义回调时,这两个参数会自动传递给函数.

When you define a callback by simply appending @ to a function name to create a function handle, these two arguments are automatically passed to the function.

您可以改编您的匿名函数以接受两个输入参数,并在不带任何输入参数的情况下调用uigetdir,从而有效地忽略默认的回调输入.

You can instead craft your anonymous function to accept two input arguments and call uigetdir with no input arguments, effectively ignoring the default callback inputs.

set(hb, 'Callback', @(s,e)uigetdir())

如果要传递起始路径和标题,可以将其从匿名函数中传递给uigetdir.

If you want to pass a start path and a title you can pass those to uigetdir from within the anonymous function.

set(hb, 'Callback', @(s,e)uigetdir('mystartpath', 'mytitle'))

这篇关于使用uigetdir作为按钮的回调,由于奇怪的无效参数而导致崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 03:07