function edit1_Callback(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit1 as text
% str2double(get(hObject,'String')) returns contents of edit1 as a double
然后在上面这段代码的下面插入如下代码:
%以字符串的形式来存储数据文本框 1 的内容. 如果字符串不是数字,
则现实空白内容
input = str2num(get(hObject,'String'));
%检查输入是否为空. 如果为空,则默认显示为 0
if (isempty(input))
set(hObject,'String','0')
end
guidata(hObject, handles);
这段代码使得输入被严格限制,我们不能试图输入一个非数字。
4.为 edit2_Callback 添加同样一段代码
5 现在我们为计算按钮添加代码来实现把数据 1 和数据 2 相加的目的。
用 3 中同样的方法在 m 文件中找到 pushbutton1_Callback 代码段 如下;
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
在上面这段代码后添加以下代码;
a = get(handles.edit1,'String');
b = get(handles.edit2,'String');
% a and b are variables of Strings type, and need to be
% converted to variables of Number type before they can
% be added together%
total = str2num(a) + str2num(b);
c = num2str(total);
% need to convert the answer back into String type to