how to created and get data for use several action in pushbutton GUI?

2 次查看(过去 30 天)
%Sample code
function a_input_Callback(hObject, eventdata, handles)
input = str2num(get(hObject,'String'));
if (isempty(input))
set(hObject,'String','0')
end
guidata(hObject, handles);
function a_input_Callback(hObject, eventdata, handles)
input = str2num(get(hObject,'String'));
if (isempty(input))
set(hObject,'String','0')
end
guidata(hObject, handles);
%for example I have push button
function add_push_Callback(hObject, eventdata, handles)
a = get(handles.a_input,'String');
b = get(handles.b_input,'String');
total = str2num(a) + str2num(b);
c = num2str(total);
set(handles.answer,'String',c);
guidata(hObject, handles);
function div_push_Callback(hObject, eventdata, handles)
a = get(handles.a_input,'String');
b = get(handles.b_input,'String');
total = str2num(a) / str2num(b);
c = num2str(total);
set(handles.answer,'String',c);
guidata(hObject, handles);
% What I want to as is, I dont want to create a = get(handles.a_input,'String');
% and b = get(handles.b_input,'String'); again and again in each button action
%just want to create it only one time and than we can call it to do use in each button.
Thanks!

回答(1 个)

Jan
Jan 2018-1-23
You have 2 "a_input_Callback" in your posted code.
You can use the same callback with different input arguments, if you want to run the same code:
function op_push_Callback(hObject, eventdata, handles, operator)
a = str2num(get(handles.a_input, 'String'));
b = str2num(get(handles.b_input, 'String'));
switch operator
case '+'
r = a + b;
case '/'
r = a / b;
otherwise
error('Bad operator: %s', operator);
end
c = num2str(total);
set(handles.answer, 'String', c);
end
Now you can define the callbacks accordingly adding the wanted operator. I'm not sure how this works in GUIDE, but it must be easy to define it as additional argument.
If handles was not changed in a callback, guidata(hObject, handles); is not needed.

类别

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