| Contents | Index |
| On this page… |
|---|
A callback is a function that you write and associate with a specific component in the GUI or with the GUI figure itself. The callbacks control GUI or component behavior by performing some action in response to an event for its component. The event can be a mouse click on a push button, menu selection, key press, etc. This kind of programming is often called event-driven programming.
The callback functions you provide control how the GUI responds to events such as button clicks, slider movement, menu item selection, or the creation and deletion of components. There is a set of callbacks for each component and for the GUI figure itself.
The callback routines usually appear in a GUI code file following the initialization code and the creation of the components. See File Organization for more information.
When an event occurs for a component, MATLAB software invokes the component callback that is associated with that event. As an example, suppose a GUI has a push button that triggers the plotting of some data. When the user clicks the button, the software calls the callback you associated with clicking that button, and then the callback, which you have programmed, gets the data and plots it.
A component can be any control device such as an axes, push button, list box, or slider. For purposes of programming, it can also be a menu, toolbar tool, or a container such as a panel or button group. See Types of GUI Components for a list and descriptions of components.
The GUI figure and each type of component has specific kinds of callbacks with which you can associate it. The callbacks that are available for each component are defined as properties of that component. For example, a push button has five callback properties: ButtonDownFcn, Callback, CreateFcn, DeleteFcn, and KeyPressFcn. A panel has four callback properties: ButtonDownFcn, CreateFcn, DeleteFcn, and ResizeFcn. You can, but are not required to, create a callback function for each of these properties. The GUI itself, which is a figure, also has certain kinds of callbacks with which it can be associated.
Each kind of callback has a triggering mechanism or event that causes it to be called. The following table lists the callback properties that are available, their triggering events, and the components to which they apply.
Callback Property | Triggering Event | Components |
|---|---|---|
Executes when the user presses a mouse button while the pointer is on or within five pixels of a component or figure. | Axes, figure, button group, panel, user interface controls | |
Control action. Executes, for example, when a user clicks a push button or selects a menu item. | Context menu, menu user interface controls | |
Reports any edit made to a value in a table with editable cells; uses event data. | uitable | |
Reports indices of cells selected by mouse gesture in a table; uses event data. | uitable | |
Control action. Executes when the push tool or toggle tool is clicked. For the toggle tool, this is independent of its state. | Push tool, toggle tool | |
Executes when the figure closes. | Figure | |
Initializes the component when it is created. It executes after the component or figure is created, but before it is displayed. | Axes, button group, context menu, figure, menu, panel, push tool, toggle tool, toolbar, user interface controls | |
Performs cleanup operations just before the component or figure is destroyed. | Axes, button group, context menu, figure, menu, panel, push tool, toggle tool, toolbar, user interface controls | |
Executes when the user presses a keyboard key and the callback's component or figure has focus. | Figure, user interface controls | |
KeyReleaseFcn | Executes when the user releases a keyboard key and the figure has focus. | Figure |
Control action. Executes when the State of a toggle tool is changed to off. | Toggle tool | |
Control action. Executes when the State of a toggle tool is changed to on. | Toggle tool | |
Executes when a user resizes a panel, button group, or figure whose figure Resize property is set to On. | Figure, button group, panel | |
Executes when a user selects a different radio button or toggle button in a button group component. | Button group | |
Executes when you press a mouse button while the pointer is in the figure window. | Figure | |
Executes when you move the pointer within the figure window. | Figure | |
Executes when you release a mouse button. | Figure | |
Executes when you press a key when the figure or any of its child objects has focus. | Figure | |
Executes when you release a key when the figure or any of its child objects has focus. | Figure | |
WindowScrollWheelFcn | Executes when the mouse wheel is scrolled while the figure has focus. | Figure |
Note User interface controls include push buttons, sliders, radio buttons, check boxes, editable text boxes, static text boxes, list boxes, and toggle buttons. They are sometimes referred to as uicontrols. Follow the links in the preceding table to see ways in which specific callbacks are used. To get specific information for a given callback property, check the properties reference page for your component, e.g., Figure Properties, Uicontrol Properties, Uibuttongroup Properties, or Uitable Properties. |
If you use figure window callbacks, the order in which they execute and whether they can be interrupted can affect the behavior of your GUI. For more information, see Control Callback Execution and Interruption.
A GUI can have many components and each component's properties provide a way of specifying which callback should run in response to a particular event for that component. The callback that runs when the user clicks a Yes button is usually not the one that runs for the No button. Each menu item also performs a different function and needs its own callback.
You attach a callback to a specific component by setting the value of the component's Callback property (described in the previous table) to the callback as a property/value pair. The property identifies the callback type and the value identifies a function to perform it. You can do this when you define the component or later on in other initialization code. Your code can also change callbacks while the GUI is being used.
Specify a component callback property value as one of the following:
A string that contains one or more MATLAB or toolbox commands to evaluate
A handle to a function that is within scope when the GUI is running
A cell array containing a string function name or a function handle, plus optional strings, constants, or variable names for arguments
You can attach a callback when you create a component by supplying the callback's property name and value (its calling sequence). You can also add or replace a callback at a later time using the set command. The examples that follow all use set, a recommended practice because some of the parameters a callback specifies might not exist or have the required values at the time a component is created.
String callbacks are the easiest type to create, because they are self-contained. They also reside in the GUI figure itself rather than in a code file. You can use string callbacks for simple purposes, but they become cumbersome if the callback action does more than one thing or requires more than one or two parameters. Strings used for callbacks must be valid MATLAB expressions, or built-in or file-based functions, and can include arguments to functions. For example:
hb = uicontrol('Style','pushbutton',...
'String','Plot line')
set(hb,'Callback','plot(rand(20,3))')The callback string 'plot(rand(20,3))', a valid MATLAB command, is evaluated whenever the button is clicked. If you then change the callback to plot a variable, for example:
set(hb,'Callback','plot(myvar)')
then the variable myvar must exist in the base workspace at the time that the callback is triggered or the callback causes an error. It does not need to exist at the time the callback is attached to the component, only when it is triggered. Before using the callback, your code can declare it:
myvar = rand(20,1);
String callbacks are the only type of callback that do not require arguments to exist as variables when they are defined. Arguments to function handle callbacks are evaluated when you define them, and therefore must exist at that time.
For some details about workspaces, see Share Data Between Workspaces and the evalin function reference page.
You can concatenate commands in a string callback. This one, for example, adds a title to the plot it creates.
set(hb,'Callback',...
'plot(myvar,''--m''); title(''String Callback'')')The most important things to remember about using function handles (a function name preceded by an at sign, for example, @my_function) are:
Function handles are names of functions within code files, not file names.
You cannot place functions within MATLAB scripts.
The function need not exist when callbacks using it are declared.
When the callback executes, the file that defines the function must be on your path.
You cannot follow the function handle in a Callback property definition with arguments unless you wrap everything in a cell array.
Your callback function declarations must include two initial arguments that Handle Graphics automatically provides, commonly called (hObject,eventdata).
These two arguments (the handle of the object issuing the callback and event data it optionally provides) must not appear in the Callback property definition.
Here is an example of declaring a callback when defining a uicontrol:
figure
uicontrol('Style','slider','Callback',@display_slider_value)Here is the definition of the function in the GUI code file. The callback prints the value of the slider when you adjust it:
function display_slider_value(hObject,eventdata) disp(['Slider moved to ' num2str(get(hObject,'Value'))]);
When you click an arrow on the slider, the output of the function looks like this:
Slider moved to 0.01 Slider moved to 0.02 ...
Both sections of code must exist in the same GUI code file. Include the one that defines the uicontrol in a function that sets up the GUI, normally the main function. Add the callback function as a subfunction or a nested function. For more information, see Subfunctions and Nested Functions.
If you need to specify arguments for a callback, you can wrap a function name string or function handle and the arguments in a cell array.
Identify the callback as a string to execute a file having that name, for example, pushbutton_callback.m.
Identify the callback as a function handle to execute a subfunction or nested function in the currently executing code file, for example, @pushbutton_callback.
The following two sections explore the differences between these two approaches.
Use Cell Arrays with Strings. The following cell array callback defines a function name as a quoted string, 'pushbutton_callback', and two arguments, one a variable name and one a string:
myvar = rand(20,1);
set(hb,'Callback',{'pushbutton_callback',myvar,'--m'})Place the function name first in the cell array and specify it as a string. When this form of callback runs, MATLAB finds and executes a file with a .m extension having the name of the first element in the cell array, passing it two standard arguments followed by any additional elements of the cell array that you specify. Place single quotes around the function name and any literal string arguments, but not around workspace variable name arguments. The function must exist on the MATLAB path, and needs to have at least two arguments. The first two (which MATLAB automatically inserts) are
The handle of the component whose callback is now being called.
Event data (a MATLAB struct that several figure and GUI component callbacks provide, but most pass an empty matrix). See Callbacks that Pass Event Data for specific details.
Be sure not to include the handle and event data arguments when you declare a component's callback (for example, set(hb,'Callback',{'pushbutton_callback',myvar,'--m'})), but do include them in the definition of the callback, as described in the following paragraph.
These two arguments are followed by whatever arguments you include when you specify the callback for the component. Code to execute 'pushbutton_callback' might look like this:
function pushbutton_callback(hObject, eventdata, var1, var2) plot(var1,var2)
The arguments you define can be variables, constants, or strings. Any variables the callback uses as arguments must exist in the current workspace at the time you define the callback property. In the above example, the value of the first argument (variable myvar) is copied into the callback when setting it. Consequently, if myvar does not currently exist, you receive an error:
??? Undefined function or variable 'myvar'.
If myvar changes or is deleted after defining the callback, the original value will still be used.
The second argument ('--m') is a string literal LineSpec that does not refer to any variable and, therefore, cannot raise an error when you specify the callback—unless the function's argument list does not include it.
To use this GUI, create a code file called pushbutton_callback.m containing the following code:
function pushbutton_callback(hObject, eventdata, var1, var2) plot(var1,var2)
When you run this GUI by pressing the push button, you see a line graph of myvar appearing as a magenta dashed line, similar to the following (graphs can differ due to using the rand function to generate data).

Because the value of myvar was copied into the callback when it was set, clicking the button always produces the same plot, even if the value of myvar changes in the base workspace.
For more information, see Defining Callbacks as a Cell Array of Strings — Special Case.
Use Cell Arrays with Function Handles. You can specify a callback function using a function handle instead of using a function name. The major benefit to using function handles is the capability to define functions on the fly—by executing code that sets a component's callback to the handle of a function defined within its scope, for example, an anonymous function. Dynamic callback assignment enables callbacks to change their behavior according to the context within which they operate or data they process. Never enclose function handles in quotes when you declare callbacks.
The following variation uses a function handle to specify pushbutton_callback as the callback routine to be executed when a user clicks Plot line.
figure;
hb = uicontrol('Style','pushbutton',...
'String','Plot line')
set(hb,'Callback',{@pushbutton_callback,myvar,'--m'})Callback is the name of the callback property. The first element of the cell array is the handle of the callback routine, and subsequent elements are input arguments to the callback. Function handles are not strings or filenames, so do not place single quote marks around them. Only use quote marks for callback arguments that are literal strings, such the linespec '--m' in the above example. The second and third elements of the cell array, the variable myvar and the string '--m', become the third and fourth argument of the callback, after hObject and eventdata.
As above, the callback is in a file named pushbutton_callback.m, which contains code such as this:
function pushbutton_callback(hObject, eventdata, var1, var2) plot(var1,var2)
As you can see from the previous examples, you can specify either a function name (enclosed in single quote marks) or a function handle (without single quote marks) in a callback using a cell array and achieve the same results. Using function handles gives you additional flexibility when your application needs to behave dynamically.
Note Unless you declare them as strings (with required arguments, as described in Use String Callbacks), do not use regular functions as callbacks. If you do, the functions can generate errors or behave unpredictably. Because MATLAB GUI component callbacks include autogenerated arguments, you cannot simply specify a regular MATLAB or toolbox function name or function handle (for example, plot or @plot) as a callback. Furthermore, callback function signatures generated by GUIDE include a third autogenerated argument, handles. To learn more about how GUIDE handles callbacks, see Customizing Callbacks in GUIDE. |
For more information on using function handles, see Function Handle Callbacks. See Kinds of Callbacks for a summary of available callbacks. See the component property reference pages for information about the specific types of callbacks each type of component supports.
Certain figure and GUI component callbacks provide data describing user-generated events in the eventdata argument. When present, it occupies the second argument to the callback. If there is no event data for a callback, the argument is an empty matrix. For example, a push button;s KeyPressFcn callback receives event data as follows.
function pushbutton1_KeyPressFcn(hObject, eventdata) % hObject handle to pushbutton1 (see GCBO) % eventdata structure with the following fields (see UICONTROL) % Key: name of the key that was pressed, in lower case % Character: character interpretation of the key(s) that was pressed % Modifier: name(s) of the modifier key(s)(i.e., control, shift) pressed
The following table lists callbacks that provide event data and the components to which they apply. Click the links to the appropriate property reference pages for details.
| GUI Component | Callbacks with Event Data | Property Reference Pages |
|---|---|---|
| Figure | KeyPressFcn, KeyReleaseFcn, WindowKeyPressFcn, WindowKeyReleaseFcn, WindowScrollWheel | Figure Properties |
| User interface control (uicontrol) | KeyPressFcn | Uicontrol Properties |
| Button group (uibuttongroup) | SelectionChangeFcn | Uibuttongroup Properties |
| Table (uitable) | CellEditCallback, CellSelectionCallback | Uitable Properties |
If you are designing a GUI and programming it yourself (outside of GUIDE), you can attach the same callback to more than one component. This is a good technique to use when a group of controls perform similar actions with small variations or operate identically on different data. In such cases, you can design a single callback function that provides separate code paths to handle each case. The callback can decide what code path to take based on the identity and type of object that calls it, or on the basis of parameters passed into it.
For an example of a callback shared by three check boxes that plot three different columns of tabular data, see GUI that Displays and Graphs Tabular Data. All three components do the same thing; the last argument in their common callback provides the number of the column to retrieve data from when plotting.
![]() | Initialize a Programmatic GUI | Examples: Program GUI Components | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |