Why Does Handles Overwrite This Variable?
조회 수: 4 (최근 30일)
이전 댓글 표시
I have created a GUI with only two push buttons and then replaced the callback functions of these two push buttons with the code below:
function pushbutton1_Callback(hObject, eventdata, handles)
handles.MyValue1 = 4;
assignin('base', 'handles', handles);
function pushbutton2_Callback(hObject, eventdata, handles)
handles.MyValue2 = 2;
assignin('base', 'handles', handles);
When I run this GUI and press pushbutton1, MyValue1 appears in the struct handles (visible in the Variables Window). When I press pushbutton2, MyValue2 appears and suddenly makes MyValue1 disappear! What is happening to MyValue1? How can I keep both MyValue1 and MyValue2 in the struct? If you know the reason, please explain it elaborately. Thanks!
댓글 수: 0
채택된 답변
Jan
2017년 3월 15일
편집: Jan
2017년 3월 15일
This is the expected behaviour. When this callback is called:
function pushbutton1_Callback(hObject, eventdata, handles)
the variable handles has the value as defined during the creation of the callback. (Please correct me, if modern versions of GUIDE update the handles struct before calling callbacks.)
Then you modify a field and store the result in teh base workspace, which means "in the command window". But this does not concern the value of handles provided in the inputs of the callbacks. The variables have the same name, but live in different workspaces.
Creating variables dynamically in the base workspace is a bad idea. This suffers from the same problems as global variables (see thousands of corresponding discussions in the net). Prefer to store the variables locally in the GUI:
function pushbutton1_Callback(hObject, eventdata, handlesFromInput)
handles = guidata(hObject); % Get current value from the GUI
handles.MyValue1 = 4;
guidata(hObject, handles); % Store modified value in the GUI
function pushbutton2_Callback(hObject, eventdata, handlesFromInput)
handles = guidata(hObject); % Get current value from the GUI
handles.MyValue2 = 2;
guidata(hObject, handles); % Store modified value in the GUI
I've renamed the "handles" in the input arguments to "handlesFromInput" to avoid confusions. The ambiguity of the "handles" struct has been the point which let me decide not to use GUIDE for my projects.
Now the handles struct is obtained dynamically from the GUI and it is stored their after changes. If you really need its value outside the GUI, export it by assignin only directly before using, e.g. when you hit a "Start" button which calls a Simulink model.
This topic is discussed frequently. Search for "share data between callbacks" in this forum.
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Migrate GUIDE Apps에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!