GUI问题,无法使用句柄来存储变量

时间:2013-03-10 17:59:30

标签: function matlab user-interface matlab-guide

我正在创建一个用户输入值的GUI,当他按下按钮时,它会运行外部函数并显示错误消息。我在GUI编码中成功插入变量时遇到问题。我很困惑在哪里插入我的变量。我试过手柄,但不幸的是它没有用。

  % --- Executes just before Stallfunction is made visible.
  function Stallfunction_OpeningFcn(hObject, ~, handles, varargin)
  % This function has no output args, see OutputFcn.
  % hObject    handle to figure
  % eventdata  reserved - to be defined in a future version of MATLAB
  % handles    structure with handles and user data (see GUIDATA)
  % varargin   command line arguments to Stallfunction (see VARARGIN)
  % Choose default command line output for Stallfunction
   handles.user_entry = user_entry;
  % Update handles structure
  guidata(hObject, handles);
  % UIWAIT makes Stallfunction wait for user response (see UIRESUME)
  % uiwait(handles.figure1);

我在上面的代码中插入了变量,'user_entry'是正确的吗?

2 个答案:

答案 0 :(得分:1)

user_entry未在您的函数中分配值。如果您通过传递user_entry的值来启动GUI:

Stallfunction(user_entry)

然后您在opensFcn中的代码的第一行应该是:

if ~isempty(varargin)
    user_entry = varargin{1};
else
    error('please start the GUI with an input value')
end

在此之后,您可以将user_entry分配给句柄结构。

答案 1 :(得分:0)

试试这个:

function num = get_num()
    fig = figure('Units', 'characters', ...
                 'Position', [70 20 30 5], ...
                 'CloseRequestFcn', @close_Callback);

    edit_num = uicontrol(...
                'Parent', fig, ...
                'Style', 'edit', ...
                'Units', 'characters', ...
                'Position', [1 1 10 3], ...
                'HorizontalAlignment', 'left', ...            
                'String', 'init', ...
                'Callback', @edit_num_Callback);  

    button_finish = uicontrol( ...
        'Parent', fig, ...
        'Tag', 'button_finish', ...
        'Style', 'pushbutton', ...
        'Units', 'characters', ...
        'Position', [15 1 10 3], ...
        'String', 'Finish', ...
        'Callback', @button_finish_Callback);            

    % Nested functions
    function edit_num_Callback(hObject,eventdata)
        disp('this is a callback for edit box');
    end            

    function button_finish_Callback(hObject,eventdata) 
        % Exit
        close(fig);
    end       

    function  close_Callback(hObject,eventdata)
        num_prelim = str2num(get(edit_num,'string'));
        if(isempty(num_prelim))
            errordlg('Must be a number.','Error','modal');
            return;
        end
        num = num_prelim;
        delete(fig);
    end

waitfor(fig);  
end

看看你是否可以搞砸了这个并得到你想要的东西。另外,学习使用嵌套函数以及回调在matlab中的工作方式。将其保存为函数文件,然后调用“num = getnum;”