Why Does Handles Overwrite This Variable?

2 ビュー (過去 30 日間)
Rightia Rollmann
Rightia Rollmann 2017 年 3 月 15 日
編集済み: Jan 2017 年 3 月 15 日
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!

採用された回答

Jan
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 件)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by