示例一:基础计算器GUI
示例二:数据可视化GUI
示例三:文件浏览与显示GUI
示例四:动态图表更新GUI
示例一代码
function simpleCalculator
% 创建基础布局
f = figure('Visible','off','Position',[360,500,450,285]);
num1Edit = uicontrol('Style','edit','Position',[315,220,100,25]);
num2Edit = uicontrol('Style','edit','Position',[315,180,100,25]);
resultText = uicontrol('Style','text','Position',[315,140,100,25],'String','Result');
addButton = uicontrol('Style','pushbutton','String','+','Position',[50,215,50,25],'Callback',{@add_Callback});
subtractButton = uicontrol('Style','pushbutton','String','-','Position',[110,215,50,25],'Callback',{@subtract_Callback});
multiplyButton = uicontrol('Style','pushbutton','String','*','Position',[50,175,50,25],'Callback',{@multiply_Callback});
divideButton = uicontrol('Style','pushbutton','String','/','Position',[110,175,50,25],'Callback',{@divide_Callback});
f.Visible = 'on';
function add_Callback(~,~)
result = str2double(get(num1Edit,'String')) + str2double(get(num2Edit,'String'));
set(resultText, 'String', num2str(result));
end
function subtract_Callback(~,~)
result = str2double(get(num1Edit,'String')) - str2double(get(num2Edit,'String'));
set(resultText, 'String', num2str(result));
end
function multiply_Callback(~,~)
result = str2double(get(num1Edit,'String')) * str2double(get(num2Edit,'String'));
set(resultText, 'String', num2str(result));
end
function divide_Callback(~,~)
result = str2double(get(num1Edit,'String')) / str2double(get(num2Edit,'String'));
set(resultText, 'String', num2str(result));
end
end
③ 代码解释
- 此代码创建了一个包含四个按钮(加、减、乘、除)和两个输入框的基础计算器GUI。
- 回调函数
add_Callback
,subtract_Callback
,multiply_Callback
,divide_Callback
分别处理不同的算术运算。 - 使用
uicontrol
函数创建GUI元素,如按钮和文本框。 - 使用
get
和set
函数来获取用户输入并显示结果。
目录