MATLAB GUI回调没有为另一个回调设置值?

时间:2013-01-16 16:42:58

标签: matlab matlab-guide handles

我想按一个按钮设置值,按另一个按钮输出变量值。似乎没有使用以下代码按下第一个按钮设置该值。那是为什么?

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.dog=1001

% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles
disp(num2str(handles.dog))   % <-- value not present

2 个答案:

答案 0 :(得分:1)

你必须在`pushbutton2_Callback的末尾写guidata(hObject, handles);来更新句柄结构,这样你就可以从其他函数访问它了。

因此,您得到的代码将是:

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.dog=1001
guidata(hObject, handles);

% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles
disp(num2str(handles.dog))   % <-- value not present

答案 1 :(得分:0)

在设置值后使用guidata(hObject, handles);来保存它

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.dog=1001

guidata(hObject, handles);