Main Content

本页翻译不是最新的。点击此处可查看最新英文版本。

uibutton

创建普通按钮或状态按钮组件

说明

btn = uibutton 在新图窗中创建一个普通按钮,并返回 Button 对象。MATLAB® 调用 uifigure 函数来创建该图窗。

示例

btn = uibutton(parent) 在指定的父容器中创建一个按钮。父容器可以是使用 uifigure 函数创建的图窗或其子容器之一。

btn = uibutton(style) 创建指定样式的按钮。按钮样式可以是 "push""state"

示例

btn = uibutton(parent,style) 在指定的父容器中创建指定样式的按钮。

示例

btn = uibutton(___,Name,Value) 创建一个按钮,其属性由一个或多个名称-值参数指定。例如,使用 BackgroundColor 属性指定按钮背景颜色。可将此选项与上述语法中的任何输入参数组合一起使用。

示例

全部折叠

在 UI 图窗中创建一个普通按钮。

fig = uifigure;
b = uibutton(fig);

Figure contains an object of type uibutton.

在 UI 图窗中创建一个状态按钮。

fig = uifigure;
b = uibutton(fig,"state");

Figure contains an object of type uistatebutton.

点击该按钮。点击该按钮后,它将保持按下状态。

State button in a UI figure. The button is in a pressed state.

在 UI 图窗中创建一个状态按钮,并通过指定属性值来自定义其外观。

fig = uifigure;
b = uibutton(fig,"state", ...
    "Text","Play", ...
    "Icon","play.png", ...
    "IconAlignment","top", ...
    "Position",[100 100 50 50]);

Figure contains an object of type uistatebutton.

确定该状态按钮是否处于按下状态。

b.Value
ans = logical
   0

以编程方式更新按钮值,使其以按下状态出现。

b.Value = true;

Figure contains an object of type uistatebutton.

创建一个 App,当 App 用户按下按钮时,它会绘制一些数据。

在名为 plotApp.m 的文件中,编写实现该 App 的函数:

  • 创建一个 UI 图窗和一个网格布局管理器,以对该 App 进行布局。

  • 在网格布局管理器中创建 UI 坐标区和一个按钮。

  • 编写名为 plotButtonPushed 的回调函数,该函数在 UI 坐标区中绘制一些数据,并将该函数赋给 ButtonPushedFcn 回调属性。有关回调的详细信息,请参阅Create Callbacks for Apps Created Programmatically

function plotApp
fig = uifigure;
g = uigridlayout(fig,[2 3]);
g.RowHeight = {'1x','fit'};
g.ColumnWidth = {'1x','fit','1x'};


ax = uiaxes(g);
ax.Layout.Row = 1;
ax.Layout.Column = [1 3];
b = uibutton(g, ...
    "Text","Plot Data", ...
    "ButtonPushedFcn", @(src,event) plotButtonPushed(ax));
b.Layout.Row = 2;
b.Layout.Column = 2;
end

function plotButtonPushed(ax)
x = linspace(0,2*pi,100);
y = sin(x);
plot(ax,x,y)
end

运行 plotApp 函数。点击按钮以绘制数据。

UI figure window with axes showing some plotted data and a Plot Data button below the axes

输入参数

全部折叠

按钮的样式,指定为以下值之一:

  • "push" - 点击一次,按钮将被按下并释放。

  • "state" - 点击一次,按钮将保持按下或释放状态,直到再次点击为止。

父容器,指定为使用 uifigure 函数创建的 Figure 对象或其子容器之一:TabPanelButtonGroupGridLayout。如果不指定父容器,MATLAB 会调用 uifigure 函数创建新 Figure 对象充当父容器。

名称-值参数

将可选的参数对组指定为 Name1=Value1,...,NameN=ValueN,其中 Name 是参数名称,Value 是对应的值。名称-值参数必须出现在其他参数之后,但参数对组的顺序无关紧要。

示例: uibutton(fig,BackgroundColor="blue")

在 R2021a 之前,使用逗号分隔每个名称和值,并用引号将 Name 引起来。

示例: uibutton(fig,"BackgroundColor","blue")

每种类型的 Button 对象支持一组不同的属性。有关每种类型的属性和描述的完整列表,请参阅相关联的属性页。

版本历史记录

在 R2016a 中推出

全部展开