matlab中多个按钮的一个功能
One function for multiple pushbuttons in matlab
我想为多个按钮设置一个功能,它们都做同样的事情,但它有不同的定义值。这样一来,当一个按钮被激活时,它不会与具有相同功能的另一个按钮混淆
您可以只定义一个通用函数并从所有按钮回调中调用它
参见the documentation for callbacks。默认情况下,回调接受两个输入参数:调用函数的对象的句柄和来自对象的事件数据结构,它可能为空,也可能不为空。您可以使用按钮的 String
或 Tag
属性,根据使用单个回调函数按下的按钮来控制 GUI 的行为。考虑以下示例:
function testGUI
handles.mainwindow = figure();
handles.mytextbox = uicontrol( ...
'Style', 'edit', ...
'Units', 'normalized', ...
'Position', [0.15 0.80 .70 .10], ...
'String', 'No Button Has Been Pressed' ...
);
handles.button(1) = uicontrol( ...
'Style', 'pushbutton', ...
'Units', 'normalized', ...
'Position', [0.05 0.05 .30 .70], ...
'String', 'Button1', ...
'Callback', {@mybuttonpress,handles} ...
);
handles.button(2) = uicontrol( ...
'Style', 'pushbutton', ...
'Units', 'normalized', ...
'Position', [0.35 0.05 .30 .70], ...
'String', 'Button2', ...
'Callback', {@mybuttonpress,handles} ...
);
handles.button(3) = uicontrol( ...
'Style', 'pushbutton', ...
'Units', 'normalized', ...
'Position', [0.65 0.05 .30 .70], ...
'String', 'Button3', ...
'Callback', {@mybuttonpress,handles} ...
);
end
function mybuttonpress(src, ~, handles)
switch src.String
case 'Button1'
handles.mytextbox.String = 'Button 1 Has Been Pressed';
case 'Button2'
handles.mytextbox.String = 'Button 2 Has Been Pressed';
case 'Button3'
handles.mytextbox.String = 'Button 3 Has Been Pressed';
otherwise
% Something strange happened
end
end
请注意,这需要 MATLAB R2014b 或更新版本才能使用点表示法访问对象属性。有关详细信息,请参阅 this blog post。
我想为多个按钮设置一个功能,它们都做同样的事情,但它有不同的定义值。这样一来,当一个按钮被激活时,它不会与具有相同功能的另一个按钮混淆
您可以只定义一个通用函数并从所有按钮回调中调用它
参见the documentation for callbacks。默认情况下,回调接受两个输入参数:调用函数的对象的句柄和来自对象的事件数据结构,它可能为空,也可能不为空。您可以使用按钮的 String
或 Tag
属性,根据使用单个回调函数按下的按钮来控制 GUI 的行为。考虑以下示例:
function testGUI
handles.mainwindow = figure();
handles.mytextbox = uicontrol( ...
'Style', 'edit', ...
'Units', 'normalized', ...
'Position', [0.15 0.80 .70 .10], ...
'String', 'No Button Has Been Pressed' ...
);
handles.button(1) = uicontrol( ...
'Style', 'pushbutton', ...
'Units', 'normalized', ...
'Position', [0.05 0.05 .30 .70], ...
'String', 'Button1', ...
'Callback', {@mybuttonpress,handles} ...
);
handles.button(2) = uicontrol( ...
'Style', 'pushbutton', ...
'Units', 'normalized', ...
'Position', [0.35 0.05 .30 .70], ...
'String', 'Button2', ...
'Callback', {@mybuttonpress,handles} ...
);
handles.button(3) = uicontrol( ...
'Style', 'pushbutton', ...
'Units', 'normalized', ...
'Position', [0.65 0.05 .30 .70], ...
'String', 'Button3', ...
'Callback', {@mybuttonpress,handles} ...
);
end
function mybuttonpress(src, ~, handles)
switch src.String
case 'Button1'
handles.mytextbox.String = 'Button 1 Has Been Pressed';
case 'Button2'
handles.mytextbox.String = 'Button 2 Has Been Pressed';
case 'Button3'
handles.mytextbox.String = 'Button 3 Has Been Pressed';
otherwise
% Something strange happened
end
end
请注意,这需要 MATLAB R2014b 或更新版本才能使用点表示法访问对象属性。有关详细信息,请参阅 this blog post。