240 likes | 365 Views
COMPSCI 101 S1 2014 Principles of Programming. 32 Simple Graphical User Interfaces. Learning outcomes. At the end of this lecture, students should be able: To create a simple GUI application using tkinter.
E N D
COMPSCI 101 S1 2014Principles of Programming 32 Simple Graphical User Interfaces
Learning outcomes • At the end of this lecture, students should be able: • To create a simple GUI application using tkinter. • To use labels, entries, buttons, and messages to create graphical user interfaces. • To pack widgets side-by-side or on top of each other using the pack manager • To layout widgets in a grid using the grid manager • To use standard dialog boxes for display messages • To process events using callback functions bound to widget’s command option • Examples: • Example 1: Using a Label • Example 2: Using the Pack Layout Manager • Example 3: Using the Grid Layout Manager • Exercise 1: Creating a number pad • Example 4: Using a Button • Example 5: Input and Output of Text • Example 6: Message Dialog Boxes COMPSCI101
Introduction • Most modern computer software employs a graphical user interface or GUI • A GUI displays text as well as small images (called icons) that represent objects such as directories, files of different types, command buttons, and drop-down menus • In addition to entering text at the keyboard, the user of a GUI can select an icon with a pointing device, such as a mouse, and move that icon around on the display COMPSCI101
The Behaviour of Terminal-Based Programs and GUI-Based Programs • Two different versions of a program from a user’s point of view: • Terminal-based user interface • Display a menu • Get the choice • Perform the required task • Graphical user interface • Both programs perform exactly the same function • However, their behaviour, or look and feel, from a user’s perspective are quite different COMPSCI101
Terminal-Based • Problems: • User is constrained to reply to a definite sequence of prompts for inputs • Once an input is entered, there is no way to change it • To obtain results for a different set of input data, user must wait for the command menu to be displayed again • At that point, the same command and all of the other inputs must be re-entered • User can enter an unrecognized command COMPSCI101
GUI-Based • Uses a window that contains various components • Called window objects or widgets • Solves problems of terminal-based version An entry field labels Can be dragged to resize window A command button COMPSCI101
Processing Events • The event loop processes the events continuously. • User-generated events (e.g., mouse clicks) trigger operations in program to respond by pulling in inputs, processing them, and displaying results COMPSCI101
Coding Simple GUI-Based Programs • There are many libraries and toolkits of GUI components available to the Python programmer • For example, tkinter and tkMessageBox • tkinter includes classes for windows and numerous types of window objects • tkMessageBox includes functions for several standard pop-up dialog boxes • tkinter is included with Python as a library. • Add an import statement in your py file. from tkinter import * COMPSCI101
Example 1: Using a Label Demo 1 • tkinter gives you the ability to create Windows with widgets in them • Definition: widget is a graphical component on the screen (button, text label, drop-down menu, scroll bar, picture, etc…) • GUIs are built by arranging and combining different widgets on the screen • Example 1: from tkinter import * root = Tk() hello = Label(root, text="Hello world!") hello.pack() root.mainloop() COMPSCI101
Steps: root = Tk() hello = Label(root, text="Hello world!") hello.pack() root.mainloop() • Create the parent window • All applications have a “root” window. This is the parent of all other widgets, you should create only one! • Create a label • A Label is a widget that holds text. The label has a parent of “root” • There are many options for the label. Options can be used as key-value pairs separated by commas. • Example: text: display one or more lines of text in a 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()) • 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! COMPSCI101
Layout Management Demo 2 • When we pack widgets into the window they always go under the previous widget • Other options (where to add this widget): • side=TOP or BOTTOM or LEFT or RIGHT • Example 2: root = Tk() go_label = Label(root, text='Go') go_label.pack(side=LEFT) stop_label = Label(root, text='Stop') stop_label.pack(side=RIGHT) root.mainloop() COMPSCI101
Grid Layout Manager Demo 3 • 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 • Example: • WARNING: Never use multiple geometry managers in one window! They are not compatible with each other and may cause infinite loops in your program!! 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=0) root.mainloop() COMPSCI101
Exercise 1Creating a number pad • Task: • Complete the following program which creates 9 labels as shown in the above picture • Code: root = Tk() labels = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] for i in range(len(labels)): root.mainloop() COMPSCI101
Grid Layout Manager Exercise 1 • Algorithm • labels[0], row = 0, col = 0 • labels[1], row = 0, col = 1 • labels[2], row = 0, col = 2 • labels[3], row = 1, col = 0 • labels[4], row = 1, col = 1 • labels[5], row = 1, col = 2 • … labels = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] Row=0, column = 2 Row=0, column = 0 COMPSCI101
Example 4: Using a Button • Button • These buttons can display text that convey the purpose of the buttons. • You can attach a function or a method to a button which is called automatically when you click the button. root = Tk() button = Button(root, text='Click it', command=clicked) button.pack() root.mainloop() COMPSCI101
Responding to Events Demo 4 • To activate a button and enable it to respond to clicks, set command to an event-handling method • Example: • The clicked() function display a message. • The button’s command attribute is set to the function def clicked(): print ("Hello World") root = Tk() button = Button(root, text='Click it', command=clicked) button.pack() root.mainloop() COMPSCI101
Event-Driven Programming • Coding phase: • Instantiate the window objects needed for this application (e.g., labels, command buttons) • Position these components in the window • Register controller methods with each window object in which a relevant event might occur • Define these controller methods • launch the GUI COMPSCI101
Input and Output of Text • Entry widget is used to accept single-line text strings from a user • A field can also contain text output by a program • If you want to display one or more lines of text that cannot be modified by the user, then you should use the Label widget. root = Tk() label1 = Label(root, text='Enter a name:') label1.grid(row=0, column=0) dataEnt1 = Entry(root) dataEnt1.grid(row=0, column=1) dataEnt1.bind('<Return>', record) mainloop() COMPSCI101
Reading the content of an entry Demo 5 • Steps: • Bind the event (when the user hits the “Enter” key with the entry box in focus) to the function • If the <Enter> key is pressed, the text in the Entry box will be printed to the IDLE window by using the get(). def record(event): print(dataEnt1.get()) ... dataEnt1 = Entry(root) dataEnt1.grid(row=0, column=1) dataEnt1.bind('<Return>', record) mainloop() COMPSCI101
Message Dialog Boxes Demo 6 • A dialog box is a small modal window that lets you ask a question, show a message or do many other things in a separate window from the main window root = Tk() button = Button(root, text="Click it", command=clicked) button.pack() root.mainloop() COMPSCI101
Using showInfo • Add an import statement: • To activate a button and enable it to respond to clicks, set command to an event-handling method • Example: • The clicked() function displays a message. • The button’s command attribute is set to the function • You can also call showwarningor showerror, The only difference will be the icon shown in the window. from tkinter.messagebox import showinfo def clicked(): showinfo(title="An Example", message="Hello World") ... button = Button(root, text="Click it", command=clicked) COMPSCI101
Exercise 2Word Count Revisit • Task: • Complete the following program which takes a piece of text as input from an entry, counts the frequency of each word in the text, and prints the dictionary using a message box. COMPSCI101
Exercise 2Word Count Revisit Ex 2 • Algorithm: COMPSCI101
Summary • A GUI-based program responds to user events by running methods to perform various tasks • tkintermodule includes classes, functions, and constants used in GUI programming • A GUI-based program is structured as a main window class • Examples of window components: labels, entry fields, and command buttons • Pop-up dialog boxes display messages and ask yes/no question • Objects can be arranged using grids • The commandattribute of a button can be set to a method that handles a button click COMPSCI101