Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 28

CompSci 280 S2 2107

Introduction to Software Development


GUI
Today’s Agenda
 Topics:
 Introduction
 GUI in Java
 Window Builder
 GUI in Python
 PyQt5
 Reading:
 Download & Install Window Builder to Eclipse
 http://download.eclipse.org/windowbuilder/WB/release/R201506241200-1/4.4/
 Download PyQt5
 https://riverbankcomputing.com/software/pyqt/download
 PyQt5 Tutorial
 https://www.tutorialspoint.com/pyqt/pyqt_tutorial.pdf

2 Lecture16
1.Introduction
Basic GUI Programming Concepts
 A graphical user interface (GUI) presents a user-friendly
mechanism for interacting with an application. output

 Pronounced “GOO-ee” Application


 Gives an application a distinctive “look-and-feel.” input

 Conventional programming:
 sequence of operations is determined
by the program
 what you want to happen, happens when you want it
 Event-driven programming: Application
GUI-based
 sequence of operations is determined draw callbacks

by the user’s interaction with the application’s interface Widgets

 anything that can happen, happens at any time output input

The User
3 Lecture16
2.GUI in Java
Implementing GUI in Java
 The Java Foundation Classes (JFC) are a set of packages
encompassing the following APIs:
 AWT – Abstract Windows Toolkit (java.awt package)
 The older version of the components
 Rely on “peer architecture”…drawing done by the OS platform on which the
application/applet is running
 Considered to be “heavy-weight” components using native GUI system elements
 Swing (Java 2, JDK 1.2+) (javax.swing package)
 Newer version of the components
 No “peer architecture”…components draw themselves
 Most are considered to be “lightweight” that do not rely on the native GUI or OS

4 Lecture16
2.GUI in Java
Containment Hierarchy
 Most UI are created by nesting controls (aka widgets/ UI elements)
into other controls (containers)
 Containment hierarchy: the way the controls of a UI are nested
 windows: actual first-class citizens of desktop; also called top-level containers
examples: frame, dialog box
 components: GUI widgets
examples: button, text box, label
 containers: logical grouping for components
example: panel Top-Level Container:
JFrame (or JDialog or JApplet)

Pane: JContentPane

Container: JScrollPane
Component: JButton
5 Component: JList Lecture16
2.GUI in Java
Simple GUI-based Input/Output: JOptionPane
 Most applications use windows or dialog boxes (also called dialogs) to
interact with the user.
 JOptionPane (package javax.swing) provides prebuilt dialog boxes for input and
output (note: the user cannot interact with the rest of the application while
dialog is displayed.)
 Displayed via static JOptionPane methods.
 For example, we use two input dialogs to obtain integers from the user
and a message dialog to display the sum of the integers the user enters.
String num1 = JOptionPane.showInputDialog("Enter first integer");
String num2 = JOptionPane.showInputDialog("Enter second integer");
int sum = Integer.parseInt(num1) + Integer.parseInt(num2);
JOptionPane.showMessageDialog(null, "The sum is " + sum,
"Sum of Two Integers", JOptionPane.PLAIN_MESSAGE);
import
javax.swing.*

6 Lecture16
2.GUI in Java
JFrame - is a Window, a Container
 A frame is a graphical window that can be used to hold other
components.
 A JFrame object is a window with a border and a title bar.
 The visible area of a JFrame object is a Container which means that we will be
able to add components, such as a JPanel object, to the JFrame object.
 Note: components are added to the top of a lightweight AWT Container – it is called
the content pane.
 Most windows that can contain Swing GUI components are instances of class
JFrame or a subclass of JFrame.
getContentPane().add(emptyLabel);

 You can use “new JPanel()” to create a panel for grouping components
into a container, which can then be added to another container
 Use the add(Component) method to add a component to the panel.

JPanel p = new JPanel();


p.add(new JButton("OK"));
7 Lecture16
2.GUI in Java
BorderLayout BorderLayoutDemo.java

 Places components in up to five areas:


north, east, south, west, and center
 These areas are specified by the BorderLayout constants:
 PAGE_START Container pane = getContentPane();
pane.setLayout(new BorderLayout());
 PAGE_END
JButton button = new JButton("Button 1 (PAGE_START)");
 LINE_START pane.add(button, BorderLayout.PAGE_START);

 LINE_END button = new JButton("Button 3 (LINE_START)");


pane.add(button, BorderLayout.LINE_START);
 CENTER ...

 All extra space is placed in the center area


 Note: alternate ways of writing:
 add(component, BorderLayout.CENTER)
 add(button, BorderLayout.NORTH)
8 Lecture16
2.GUI in Java
Building GUI with WindowBuilder
 WindowBuilder is composed of the following major components
 Source View
 Design View
 Component Tree
 Property Pane
 Palette
 Wizards
 Toolbars & Context Menus

9 Lecture16
2.GUI in Java
Widgets & Layout Managers
 Fully supports all standard widgets
and layout managers as well
as select third-party widgets
and layout managers

10 Lecture16
2.GUI in Java
Graphical Menu Editing
 Supports WYSIWYG Graphical Menu Editing
 Graphical edit menubars and menuitems
 Use drag/drop to rearrange menus
 Direct edit menu labels

11 Lecture16
2.GUI in Java
WindowBuilder - Installation
 Visit the following link:
 http://www.eclipse.org/windowbuilder/download.php
 Check your version of Eclipse and click the “Link” button
 Copy the URL at the top of the page
 Start Eclipse
 Choose Help -> “Install New Software”
 Copy the link into “Work with”
 Select Swing Designer, SWT Designer and WindowBuilder Engine
 Click the “Next button”

12 Lecture16
2.GUI in Java
WindowBuilder – Create a new Application
 File>New>Java Project
 Enter a name for your project
 Project Layout:
 It is a good idea to choose: “Use project folder as root for sources and class files
(i.e. .java and .class files are all in the same folder in your workspace (Workspace
is the place where your projects are created and stored. E.g.
C:\Users\name\workspace
 click ‘Finish’
 New -> Other -> WindowBuilder -> Swing Designer -> JFrame (Add a
JFrame to your project)
 Choose a package and class name

13 Lecture16
2.GUI in Java
WindowBuilder User Interface
Palette of
GUI controls

Containment
hierarchy
Visual GUI
editor

Source code of the Properties of


14 GUI selected control Lecture16
2.GUI in Java
Creating components
 Switch between code and UI using the tabs at the bottom of the
editor
 Source / Design
 Select “contentPane” in Components view
 In Properties view: set the Layout to …
 BorderLayout, OR
 “(absolute)” to allow free placement of controls
 Add components from the Palette view
 Drag & drop
 Click on the JFrame and Right-click, choose Test/Preview, or
 Run the application using “Run” as Java app
15 Lecture16
2.GUI in Java
Event Handlings
 Events occur when the user interacts with the UI. The appropriate event-
handling code is then executed.
 In order to know when events occur, event handlers must first be added to your
components.
 Event handler: method that is called when a particular event occurs
 Event handler is method in “event listener” object
 For each type of event a particular method of a particular event listener
 Adding an Event Handler
 Double-click on the button, an action event listener will be created and will
switch to the Source view and go directory to the handler method.
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//complete this

}
16 }); Lecture16
3.GUI in Python
tkinter
 tkinter is not the only GUI-programming toolkit for Python but it is the
most commonly used one.
 tkinter includes classes for windows and numerous types of window objects
 tkinter gives you the ability to create windows with widgets in them
 GUI are built by arranging and combining different widgets on the screen
 Steps:
 Create the parent window
 All applications have a “root” window. This is the parent of all other widgets.You
should create only one!
 Start the event loop ( root.mainloop() )
 Windows go into an “event loop” where they wait for things to happen (buttons
pushed, etc…). You must tell the root window to enter its event loop or the window
won’t be displayed!
root = Tk()
root.mainloop()
17 Lecture16
3.GUI in Python
A first tkinter program
 A first program using tkinter.
from tkinter import * #import the tkinter module

def main():
root = Tk() #Create an empty window
root.mainloop() #Pause the code and do nothing
#until the window is closed
main()

 Note:
 This window is the top level window to which we will add other
components (widgets).
 In this program, the variable, root, represents the top level window.

18 Lecture16
3.GUI in Python
Widgets
 Widgets are objects which can be added to our top level window. These will
allow the user to interact with the program. Some widget examples:
Buttons, Checkbuttons, Radiobuttons, Menubuttons,
Entry (for text field entries)
Message (for displaying text messages to the user)
Labels (text captions, images)
Frames (a container for other widgets)
Scale, Scrollbar
Canvas (for drawing shapes, …)
Text (for displaying and editing text) and others..
 Example: Add a Label
 Create a label
 When creating the Label widget we need to pass the top level windows, root, (in which the label
will be placed) as the first argument.
 We also need to pass the text which is to be displayed inside the Label.
 Define the position of the label ( hello.pack() )
 Tell the label to place itself into the root window and display.
 Start the event loop ( root.mainloop() ) root = Tk()
hello = Label(root, text="Hello world!")
hello.pack()
root.mainloop()
19 Lecture16
3.GUI in Python Place label widgets on top of
Layout Management each other and centre them

 The job of arranging the widgets in the window!


 When we pack widgets into the window they always go under the previous
widget root = Tk()
a_label1 = Label(root, text = "A Label widget in a window")
a_label2 = Label(root, text = "Another one")
a_label3 = Label(root, text = "And more!")
a_label1.pack()
a_label2.pack()
a_label3.pack()

 Python has other geometry managers (instead of pack) to create any


GUI layout you want
 Grid – lets you specify a row, column grid location and how many rows and
columns each widget should span
root = Tk()
go_label = Label(root, text='Go')
go_label.grid(row=0, column=0)
stop_label = Label(root, text='Stop')
stop_label.grid(row=1, column=1)
20 root.mainloop() Lecture16
3.GUI in Python
Event Handling
 Button:
 To activate a button and enable it to respond to clicks, set command to
an event-handling method
 A Python function or method can be associated with a button. This function or
method will be executed, if the button is pressed in some way.

from tkinter import *


class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.button = Button(frame,text="QUIT", fg="red",command=quit)
self.button.pack(side=LEFT)
self.slogan = Button(frame,text="Hello",command=self.write_slogan)
self.slogan.pack(side=LEFT)
def write_slogan(self): The write_slogan()
print("Tkinter is easy to use!") method is associated to
the button click event.
root = Tk()
app = App(root)
21 root.mainloop() Lecture16
3.GUI in Python
PyQt5
 PyQt is a multi-platform GUI toolkit. It has approximately ~1000
classes divided into a set of ~38 modules.
 QtCore contains the core classes, including the event loop and Qt’s
signal and slot mechanism.
 QtGui contains classes for windowing system integration, event handling,
2D graphics, basic imaging, fonts and text.
 QtWidgets contains classes that provide a set of UI elements to create
classic desktop-style user interfaces.

22 Lecture16
3.GUI in Python
Installation
 Go to the following link to download PyQt5.
 https://sourceforge.net/projects/pyqt/files/PyQt5/PyQt-5.5/
 Note: check your Python Version in your own machine.
 E.g. PyQt5-5.5-gpl-Py3.4-Qt5.5.0-x64.exe for Python Version 3.4
 Install the program
 Start PyQt5
 Go to C:\python34\Lib\site-packages\PyQt5\
 Double-click “designer.exe”
 Choose a templet from the existing templets
 Note: The designed form is saved as demo.ui. This design is
translated into Python equivalent by using pyuic5 command line
utility. pyuic5 –x demo.ui –o demo.py
23 Lecture16
PyQt5
 A Simple Example:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def b1_clicked():
print ("Button 1 clicked")
def window():
def b2_clicked():
app = QApplication(sys.argv)
print ("Button 2 clicked")
win = QDialog()
b1= QPushButton(win)
b1.setText("Button1")
b1.move(50,20)
b1.clicked.connect(b1_clicked)

b2=QPushButton(win)
b2.setText("Button2")
b2.move(50,50)
b2.clicked.connect(b2_clicked)
win.setGeometry(100,100,200,100)
win.setWindowTitle("PyQt")
win.show()
sys.exit(app.exec_())
24 Lecture16
PyQt5 def main():

Creating an application
app = QApplication(sys.argv)
w = MyWindow()
w.showMaximized()
 Step 1: w.resize(400, 200)
sys.exit(app.exec_())
 Create an application if __name__ == "__main__":
 Create and show the main window main()

 Run the event loop then exit


 Step 2:
 Create the main window
 Extends QWidget
 Write the constructor: def __init__(self, *args):
 Creating a child widget and place it in a layout
class MyWindow(QWidget):
def __init__(self, *args):
QWidget.__init__(self, *args)
...

25 Lecture16
PyQt5
Widgets
 QLabel
 QPushButton
 QLineEdit: a widget is a one-line text editor.
 QTextEdit: a widget that is used to edit and display both plain and
rich text.
 QMessageBox
okButton = QPushButton("OK")

cancelButton = QPushButton("Cancel")

self.nameLabel = QLabel("Name:")
self.nameEdit = QLineEdit()

26 Lecture16
PyQt5
Using Layouts
 Layouts manage child widgets and are responsible for:
 Updating their sizes and positions
 Providing default and minimum sizes
 Horizontal, vertical and grid layouts:
 QHBoxLayout()
 QVBoxLayout()
 QGridLayout()

oneButton = QPushButton("One")
twoButton = QPushButton("Two")
threeButton = QPushButton("Three")
layout = QHBoxLayout(self)
layout.addWidget(oneButton)
layout.addWidget(twoButton)
layout.addWidget(threeButton)

27 Lecture16
PyQt5
Event Handling
 Widgets used to build the GUI interface act as the source of such
events. Each PyQt widget, which is derived from QObject class, is
designed to emit ‘signal’ in response to one or more events.
 The signal on its own does not perform any action. Instead, it is
‘connected’ to a ‘slot’. The slot can be any callable Python function.
 In PyQt, connection between a signal and a slot can be achieved in
different ways. Following are most commonly used techniques:
oneButton.clicked.connect(self.show_one)

def show_one(self):
self.messageEdit.setText("ONE")

28 Lecture16

You might also like