Compsci 280 S2 2107 Introduction To Software Development
Compsci 280 S2 2107 Introduction To Software Development
2 Lecture16
1.Introduction
Basic GUI Programming Concepts
A graphical user interface (GUI) presents a user-friendly
mechanism for interacting with an application. output
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
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.
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
}
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
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()
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