2013-01-16 55 views
0

我想要一個按鈕來設置數值,另一個按鈕按下來輸出一個變量的值。看起來這個值不是通過使用下面的代碼按下第一個按鈕來設置的。這是爲什麼?MATLAB的GUI回調沒有設置另一個回調的值?

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

回答

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