2013-03-10 42 views
1

我正在创建一个用户输入一个值的图形用户界面,当他按下一个按钮时,它会运行一个外部函数并显示错误消息。我无法在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”的变量是正确的吗?

回答

1

user_entry未在您的函数中分配一个值。如果你通过传递一个值user_entry这样启动您的GUI:

Stallfunction(user_entry) 

那么你的代码在openingFcn第一行应该是:

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

在此之后,您可以指定user_entry到处理结构,你已经在做。

+0

GUI不通过传递值来启动。我有GUI界面,然后我在编辑框中输入一个值并按下按钮来运行另一个功能。你指的是同一件事吗? – user1860036 2013-03-10 19:28:13

+0

@ user1860036:在这种情况下,您必须填写编辑框的回调,以便将该框的内容写入'handles.user_entry'中。 – Jonas 2013-03-10 21:00:39

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;”