1

我正在创建一个 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”,对吗?

4

2 回答 2

1

user_entry is not assigned a value in your function. If you launch your GUI by passing a value for user_entry like this:

Stallfunction(user_entry)

then the first lines of your code in the openingFcn should be:

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

After this, you can assign user_entry to the handles structure as you're doing already.

于 2013-03-10T18:27:51.530 回答
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;”

于 2013-03-11T00:31:49.347 回答