Download presentation
Presentation is loading. Please wait.
Published byDennis Reed Modified over 7 years ago
1
CompSci 280 S2 2107 Introduction to Software Development
GUI
2
Today’s Agenda Topics: Reading: Introduction GUI in Java GUI in Python
Window Builder GUI in Python PyQt5 Reading: Download & Install Window Builder to Eclipse Download PyQt5 PyQt5 Tutorial Lecture16
3
1.Introduction Basic GUI Programming Concepts
A graphical user interface (GUI) presents a user-friendly mechanism for interacting with an application. Pronounced “GOO-ee” Gives an application a distinctive “look-and-feel.” Conventional programming: sequence of operations is determined by the program what you want to happen, happens when you want it Event-driven programming: sequence of operations is determined by the user’s interaction with the application’s interface anything that can happen, happens at any time Application output input Application Widgets The User draw output input callbacks GUI-based Lecture16
4
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 Lecture16
5
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 Lecture16 Component: JList
6
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.* Lecture16
7
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. 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. getContentPane().add(emptyLabel); JPanel p = new JPanel(); p.add(new JButton("OK")); Lecture16
8
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 PAGE_END LINE_START LINE_END CENTER All extra space is placed in the center area Note: alternate ways of writing: add(component, BorderLayout.CENTER) add(button, BorderLayout.NORTH) Container pane = getContentPane(); pane.setLayout(new BorderLayout()); JButton button = new JButton("Button 1 (PAGE_START)"); pane.add(button, BorderLayout.PAGE_START); button = new JButton("Button 3 (LINE_START)"); pane.add(button, BorderLayout.LINE_START); ... Lecture16
9
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 Lecture16
10
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 Lecture16
11
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 Lecture16
12
2.GUI in Java WindowBuilder - Installation
Visit the following link: 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” Lecture16
13
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 Lecture16
14
2.GUI in Java WindowBuilder User Interface
Palette of GUI controls Containment hierarchy Visual GUI editor Source code of the GUI Properties of selected control Lecture16
15
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 Lecture16
16
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 } }); Lecture16
17
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! To display one or more lines of text in a label widget root = Tk() root.mainloop() Lecture16
18
3.GUI in Python A first tkinter program
A first program using tkinter. 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. 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() Lecture16
19
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: 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() ) 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.. root = Tk() hello = Label(root, text="Hello world!") hello.pack() root.mainloop() Lecture16
20
3.GUI in Python Layout Management
Place label widgets on top of 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 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() 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() 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) root.mainloop() Lecture16
21
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): print("Tkinter is easy to use!") root = Tk() app = App(root) root.mainloop() The write_slogan() method is associated to the button click event. Lecture16
22
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. Lecture16
23
3.GUI in Python Installation
Go to the following link to download PyQt5. 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 Lecture16
24
PyQt5 A Simple Example: import sys from PyQt5.QtCore import *
from PyQt5.QtGui import * from PyQt5.QtWidgets import * def window(): app = QApplication(sys.argv) 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_()) def b1_clicked(): print ("Button 1 clicked") def b2_clicked(): print ("Button 2 clicked") Lecture16
25
PyQt5 Creating an application
def main(): app = QApplication(sys.argv) w = MyWindow() w.showMaximized() w.resize(400, 200) sys.exit(app.exec_()) if __name__ == "__main__": main() Step 1: Create an application Create and show the main window 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) ... Lecture16
26
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() Lecture16
27
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) Lecture16
28
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") Lecture16
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.