51

GUI -THESIS123

Embed Size (px)

Citation preview

Page 1: GUI -THESIS123
Page 2: GUI -THESIS123

GUI• Graphical User Interface-A tool for interacting with the

computer• A graphical user interface (GUI) is a pictorial interface to

a program.

• A good GUI can make programs easier to use by providing them with a consistent appearance and with intuitive controls like pushbuttons, list boxes, sliders, menus, and so forth.

• The GUI should behave in an understandable and predictable manner, so that a user knows what to expect when he or she performs an action. For example, when a mouse click occurs on a pushbutton, the GUI should initiate the action described on the label of the button.

Page 3: GUI -THESIS123

How is this useful?• Visually interaction with data is often

simpler and more intuitive

• Faster manipulation of data

• Interactive

• Easy to Learn!

• Proof

Page 4: GUI -THESIS123

How a GUI works• There are three principal

element to create a Matlab Graphical User Interface. 1. Components

2. Containers

3. Callbacks

Page 5: GUI -THESIS123

•Each item on a MATLAB GUI (pushbuttons,labels, edit boxes, etc.) is a graphical component. The types of components include

– graphical controls pushbuttons,edit boxes, lists, sliders, togglebutons etc.,

– static elements (frames and text strings)– menus– Toolbars– and axes.

•Graphical controls and static elements are created by the function uicontrol•menus are created by the functions uimenu and uicontextmenu•Tool bars are created by the function uitoolbar• Axes, which are used to display graphical data, are created by the function axes

Components

Page 6: GUI -THESIS123

Containers

• The components of a GUI must be arranged within a container which is a window on the computer.

• Figure –Most commonly used• Panels-uipanel• Button groups-uibutton-group

Page 7: GUI -THESIS123

callbacks

• Event- action performed by the user (mouse click)

• Callback- The code executed in response to an event

Page 8: GUI -THESIS123

Some basic GUI components• Component Created by Description• Figure figure Creates a figure which is a container

that can hold components and other containers. Figures are separate windows that have the title tool bar and can have menus

• Panel uipanel Creates panel which is a container that can hold components and other containers. Unlike figures panels do not have title bar or menus. Panel can be placed inside the figures or other panels

• Button group uibuttongroup Creates a button group which is a special kind of panel. Button groups automatically manage groups of radio buttons or toggle buttons to ensure that only one item of the group is on at any

given time

Page 9: GUI -THESIS123
Page 10: GUI -THESIS123

• Component Created by Description• Toolbar – uitoolbar Creates a toolbar, which is a bar across

the top of the figure containing the quick access buttons

• Toolbar pushbutton- uipushtool creates a pushbutton to go in a toolbar

• Toolbar Toggle- uitoggletool creates toggle tool button to go in a tool bar

Page 11: GUI -THESIS123

Push ButtonsRadio Buttons

Frames

Checkbox Slider

Edit text

static textAxes

Page 12: GUI -THESIS123

Property Inspector

Align Objects

Menu

editor

Tab

Order

Editor

Object browser

GUIDE Compo-

nents

Design area

Drag to resize Design Area

GUIDE EDITOR

Page 13: GUI -THESIS123

Guide Editor

Property Inspector

Result Figure

Page 14: GUI -THESIS123

The basic stepsrequired to create a MATLAB GUIDE

1. Decide what elements are required for the GUI and what the function of each element will be. Make a rough layout of the components by hand on a piece of paper.

2. Use a MATLAB tool called guide (GUI Development Environment) to layout the Components on a figure. The size of the figure and the alignment and spacing of components on the figure can be adjusted using the tools built into guide.

3. Use a MATLAB tool called the Property Inspector (built into guide) to give each component a name (a "tag") and to set the characteristics of each component, such as its color, the text it displays, and so on.

Page 15: GUI -THESIS123

4. Save the figure to a file. When the figure is saved, two files will be created on disk with the same name but different extents. The fig file contains the actual GUI that you have created, and the M-file contains the code to load the figure and skeleton call backs for each GUI element.

5. Write code to implement the behavior associated with each callback function.

Page 16: GUI -THESIS123

As an example of these steps, let's consider a simple GUI that contains a singlepushbutton and a single text string. Each time that the pushbutton is clicked, the text string will be updated to show the total number of clicks since the GUI started.

• Step 1: The design of this Gm is very simple. It contains a single pushbutton and a single text field. The callback from the pushbutton will cause the number displayed in the text field to increase by one each time that the button is pressed. A rough sketch of the GUI is shown in Figure

Pushbutton

Total clicks: 0

Figure

Text field

Pushbutton

Page 17: GUI -THESIS123

Step 2

• To layout the components on the GUI, run the MATLAB function guide. Whenguide is executed, it creates the window shown in figure.

Page 18: GUI -THESIS123

• First, we must set the size of the layout area, which will become the size the final GUI.

• We do this by dragging the small square on the lower right corner of the layout area until it has the desired size and shape. Then, click on the "pushbutton" button in the list of GUI components, and create the shape of the pushbutton in the layout area.

• Finally, click on the "text" button in the list GUI components, and create the shape of the text field in the

layout area. The resulting figure after these steps is shown in Figure.

• We could now adjust the alignment of these two elements using the Alignment Tool, if desired.

Page 19: GUI -THESIS123

Step 3• To set the properties of the

pushbutton, click on the button in the layout area and

• then select "Property Inspector" from the toolbar. Alternatively, right-click on the button

• and select "Inspect Properties" from the popup menu. The Property Inspector window shown in Figure 1.5 will appear. Note this window lists every property available for the

• pushbutton and allows us set each value using a GUI interface. The Property Inspector

• performs the same function as the get and set functions, but in a much more convenient

• form.

Page 20: GUI -THESIS123

• Editing

• For the pushbutton, we may set many properties such as color, size, font, text alignment, and so on. However, we must set two properties: the String property, which contains the text to be displayed, and the Tag property, which is the name of the pushbutton.

• In this case, the String property will be set to 'click Here', and the Tag property will be set to MyFirstButton.

• For the text field, we must set two properties: the String property, which contains the text to be displayed, and the Tag property, which is the name of the text field. This name will be needed by the callback function to locate and update the text field. In this case, the String property will be set to 'Totalclicks: 0', and the Tag property defaulted to 'MyFirstText'.

• It is possible to set the properties of the figure itself by clicking on a clear spot in the Layout Editor, and then using the Property Inspector to examine and set the figure's properties.

• Although not required, it is a good idea to set the figure's Name property. The string in the Name property will be displayed in the title bar of the resulting GUI when it is executed.

Page 21: GUI -THESIS123

Step 4• We will now save the layout area

under the name MyFirstGUI. • Select the "File/SaveAs" menu

item, type the name MyFirstGUI as the file name, and click "Save".

• This action will automatically create two files, FirtstExample.fig and FirtstExample.m.

• The figure file contains the actual GUI that we have created.

• The M-file contains code that loads the figure file and creates the GUI, plus a skeleton callback function for each activeGUI component.

Page 22: GUI -THESIS123

Step 5• Now, we need to implement the callback sub function for

the pushbutton. • This function will include a persistent variable that can be

used to count the number of clicks that have occurred. • When a click occurs on the pushbutton, MATLAB will call

the function FirtstExample with MyFirstButton_callback as the first argument.

• Then function FirtstExample will call sub function MyFirstButton_callback, as shownin Figure 1.9.

• This function should increase the count of clicks by one, create a new text string containing the count, and store the new string in the String property of the text field MyFirstText.

Page 23: GUI -THESIS123

function varargout = FirstExample(varargin)% FIRSTEXAMPLE M-file for FirstExample.fig% FIRSTEXAMPLE, by itself, creates a new

FIRSTEXAMPLE or raises the existing% singleton*.%% H = FIRSTEXAMPLE returns the handle to a

new FIRSTEXAMPLE or the handle to% the existing singleton*.%%

FIRSTEXAMPLE('CALLBACK',hObject,eventData,handles,...) calls the local

% function named CALLBACK in FIRSTEXAMPLE.M with the given input arguments.

% FIRSTEXAMPLE('Property','Value',...) creates a new FIRSTEXAMPLE or raises the

% existing singleton*. Starting from the left, property value pairs are

% applied to the GUI before FirstExample_OpeningFunction gets called. An

% unrecognized property name or invalid value makes property application

% stop. All inputs are passed to FirstExample_OpeningFcn via varargin.

%

% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one

% instance to run (singleton)".% See also: GUIDE, GUIDATA, GUIHANDLES% Edit the above text to modify the response to help

FirstExample % Last Modified by GUIDE v2.5 29-Jun-2008 13:39:06 % Begin initialization code - DO NOT EDITgui_Singleton = 1;gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn',

@FirstExample_OpeningFcn, ... 'gui_OutputFcn', @FirstExample_OutputFcn,

... 'gui_LayoutFcn', [] , ... 'gui_Callback', []);if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1});endif nargout [varargout{1:nargout}] = gui_mainfcn(gui_State,

varargin{:});else gui_mainfcn(gui_State, varargin{:});end% End initialization code - DO NOT EDIT

Main Function

Page 24: GUI -THESIS123

% --- Executes just before FirstExample is made visible.

function FirstExample_OpeningFcn(hObject, eventdata, handles, varargin)

% This function has no output args, see OutputFcn.

% hObject handle to figure% eventdata reserved - to be

defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

% varargin command line arguments to FirstExample (see VARARGIN)

% Choose default command line output for FirstExample

handles.output = hObject; % Update handles structureguidata(hObject, handles); % UIWAIT makes FirstExample

wait for user response (see UIRESUME)

% uiwait(handles.figure1); % --- Outputs from this function

are returned to the command line.

Figure Opening Function

Page 25: GUI -THESIS123

Data OutputFnctionfunction varargout = FirstExample_OutputFcn(hObject,

eventdata, handles) % varargout cell array for returning output args (see

VARARGOUT);% hObject handle to figure% eventdata reserved - to be defined in a future version

of MATLAB% handles structure with handles and user data (see

GUIDATA) % Get default command line output from handles

structurevarargout{1} = handles.output;

Page 26: GUI -THESIS123

Button Callback Function% --- Executes on button press in myfirstbutton.function myfirstbutton_Callback(hObject, eventdata,

handles)% hObject handle to myfirstbutton (see GCBO)% eventdata reserved - to be defined in a future version

of MATLAB% handles structure with handles and user data (see

GUIDATA)

Page 27: GUI -THESIS123
Page 28: GUI -THESIS123
Page 29: GUI -THESIS123

Button Callback Function% --- Executes on button press in myfirstbutton.function myfirstbutton_Callback(hObject, eventdata, handles)% hObject handle to myfirstbutton (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)% Declare and intialise variable to store the count persistent countpersistent countNote: this function declares a persistent variable count and initializes

it to zero.if isempty(count)count=0;end%Update Countcount=count+1;%Create new String str=sprintf('Total Clicks: %d',count);%Update the text fieldset(handles.myfirsttext,'string',str);

Page 30: GUI -THESIS123

Some Examples

Page 31: GUI -THESIS123

Components of a GUI• Front End

– point of interaction with user• Back End

– where the action is, the code controlling the graphics and the different widgets

Page 32: GUI -THESIS123

Components of a GUI• Front End

– Select and place different objects (widgets) on the graphical layout. These will the what the user interacts with.

– Underlying the GUI is the backend which controls how the GUI reacts on an event.

– This is called event-driven programming

Page 33: GUI -THESIS123

Components of a GUI• Back End

– The code underlying the frontend graphics.– Matlab gives a basis and you fill in the details

Page 34: GUI -THESIS123

In Matlab• Matlab provides interactive tool for creating the

graphics and underlying code for GUIs– Function is called GUIDE– Provides some templates for simple GUIs that

can be expanded as need be• Launch GUIDE in Matlab and select on of the pre-

made templates (ie. not Blank)

Page 35: GUI -THESIS123

GUI with Axis and Menu• This is the layout for a simple GUI that allows you to

select one of 5 pre-made plots.• Not very useful but a good basis to start with• Press the Launch button and save• You will see the screen and you can interact with it

Page 36: GUI -THESIS123

Backend of Axis and Menu

• When you launch the GUI created the .fig file which is the graphics and the .m file which is the underlying code that control the widget.

– Take a Look at the .m file– It looks like a mess, but it is not so bad!

• Lets explore this code

• First lets understand the basic m-file format template for an empty GUI

Page 37: GUI -THESIS123

Common Input Arguments

All functions in the M-file have the following input arguments corresponding to the handles structure:

• hObject -- the handle to the figure or Callback object

• handles -- structure with handles and user data

The handles structure is saved at the end of each function with the command:

guidata(hObject, handles);

Functions and Callbacks in the M-File

Page 38: GUI -THESIS123

Sharing Data with the Handles Structure

• When you run a GUI, the M-file creates a handles structure that contains all the data for GUI objects, such as controls, menus, and axes.

• The handles structure is passed as an input to each callback (user interface). • You can use the handles structure to Share data between callbacks using the ‘guidata’ function

Functions and Callbacks in the M-File

Page 39: GUI -THESIS123

Sharing Data

To store data that is contained in a variable X, set a field of the handles structure equal to X and then save the handles structure with the guidata function:

handles.current_data = X;guidata(hObject,handles)

You can retrieve the data in any other callback with the command:

X = handles.current_data;

Functions and Callbacks in the M-File

Page 40: GUI -THESIS123

You can add code to the following parts of the GUI M-file:

• Opening function -- executes before the GUI becomes visible to the user.

• Output function -- outputs data to the command line, if necessary.

• Callbacks -- execute each time the user activates the corresponding component of the GUI.

Functions and Callbacks in the M-File

Page 41: GUI -THESIS123

Opening Function

• The opening function contains code that is executed just before the GUI is made visible to the user. • You can access all the components for the GUI in the opening function, because all objects in the GUI are created before the opening function is called. • You can add code to the opening function to perform tasks that need to be done before the user has access to the GUI

This includes:

creating data, plots or images, or making the GUI blocking with the uiwait command.

Functions and Callbacks in the M-File

Page 42: GUI -THESIS123

uiwait

• The command uiwait makes the M-file halt execution This is useful to force the program to pause execution until a user activates a some component in the GUI.

• The uiresume command allows the M-file to resume execution once the user input is complete

Page 43: GUI -THESIS123

Opening Function

For a GUI whose file name is my_gui, the definition line for the opening function is:

function my_gui_OpeningFcn(hObject, eventdata, handles, varargin)

Besides the arguments hObject and handles, the opening function has the following input arguments:

• eventdata -- reserved for a future version of MATLAB • varargin -- command line arguments to untitled

Functions and Callbacks in the M-File

Page 44: GUI -THESIS123

Opening Function (varargin)

• All command line arguments are passed to the opening function via varargin. • If you open the GUI with a property name/property value pair as arguments, the GUI opens with the property set to the specified value.

For example:

my_gui('Position', [71.8 44.9 74.8 19.7])

opens the GUI at the specified position, since Position is a valid figure property

Functions and Callbacks in the M-File

Page 45: GUI -THESIS123

Output Function

The output function returns output arguments to the command line.

GUIDE generates the following output function:

% --- Outputs from this function are returned to the command line.function varargout = my_gui_OutputFcn(hObject, eventdata, handles)% Get default command line output from handles structurevarargout{1} = handles.output;

Functions and Callbacks in the M-File

Page 46: GUI -THESIS123

Callbacks

• When a user activates a component of the GUI, the GUI executes the corresponding callback.

• The name of the callback is determined by the component's Tag property and the type of callback.

For example, a push button with the Tag print_button executes the callback: function print_button_Callback(hObject, eventdata, handles)

Functions and Callbacks in the M-File

Page 47: GUI -THESIS123

Output Function

• By default the output is the handle to the GUI, which is assigned to handles.output in the opening function.

• To make the GUI return a different output (eg. return the result of a user response, such as pressing a push button):

% Add the command uiwait to the opening function % For each component of the GUI where you expect a user response, make the callback update the value of handles.output, and execute uiresume.

handles.output = ‘some response string';guidata(hObject, handles);uiresume;

Functions and Callbacks in the M-File

Page 48: GUI -THESIS123

Property Inspector• Adjusts the details of the different widgets

Page 49: GUI -THESIS123

Something Useful?• Now, lets try and build something that we may

actually use. How about a simple program that combines loading, plotting and calculating some simple statistics on preformatted data

• Create a GUI that will load ‘week8_testdata2.txt’, plot the data points as well as a linear regression

Hint, All you need are simple push buttons and an axis for plotting

Page 50: GUI -THESIS123

Push Buttons

• Work like independent functions

• Each button function is passed all data from the GUI handles

% --- Executes on button press in Exit.function Exit_Callback(hObject, eventdata, handles)% hObject handle to Exit (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)close gcf

• Detailed descriptions of all GUI callback controls can be found within the GUIDE help menu.

Programming GUI controls

Page 51: GUI -THESIS123

Layout the GUI