Why Does Handles Overwrite This Variable?

2 次查看(过去 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!

采纳的回答

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

类别

Help CenterFile Exchange 中查找有关 Interactive Control and Callbacks 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by