首先应设计好计算器的GUI界面 如下图所示,然后分别设置‘数据1’、‘数据2’、‘计算结果’的tag值为num1、num2和shuchu当然你要是愿意也可以定义加减乘除按钮的tag属性,tag属性值也就是你的控件名字,给它取了名字就可以赋予它使命,要它执行命令了。
接着为加减乘除按钮编写回调函数:
加法按钮回调函数:
% --- Executes on button press in plus.
function plus_Callback(hObject, eventdata, handles)
% hObject handle to plus (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
shuchu = handles.num1+handles.num2;
set(handles.shuchu, 'String', shuchu);减法按钮回调函数:
% --- Executes on button press in pushbutton7.
function pushbutton7_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton7 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
shuchu = handles.num1-handles.num2;
set(handles.shuchu, 'String', shuchu);乘法按钮回调函数:
% --- Executes on button press in pushbutton5.
function pushbutton5_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
shuchu = handles.num1*handles.num2;
set(handles.shuchu, 'String', shuchu);除法按钮回调函数:
% --- Executes on button press in pushbutton6.
function pushbutton6_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton6 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
shuchu = handles.num1/handles.num2;
set(handles.shuchu, 'String', shuchu);回调函数的名字结构是由控件名字(tag值)与Callback通过‘—’连接而成
回调函数的作用是实现当控件被触发时执行函数命令
当然你也可以象我一样为你的GUI加一个退出按钮实现退出窗口;
退出窗口回调函数:
% --- Executes on button press in tuichu.
function tuichu_Callback(hObject, eventdata, handles)
% hObject handle to tuichu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close('AandB');
如果觉得《matlab gui教程 计算器 matlab gui编写的计算器程序》对你有帮助,请点赞、收藏,并留下你的观点哦!