0

我想要一个按钮来设置值,另一个按钮来输出变量的值。似乎使用以下代码第一次按下按钮时未设置该值。这是为什么?

% --- 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
4

2 回答 2

1

guidata(hObject, handles);您必须在 `pushbutton2_Callback 的末尾写入以更新句柄结构,以便您可以从其他函数访问它。

因此,您生成的代码将是:

% --- 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
于 2013-01-16T16:48:37.637 回答
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);
于 2013-01-16T16:48:04.200 回答