Transcript WEEK 12-13 - State University of Zanzibar
WEEK 12-13
Introduction to GUI programming
Introduction
• • Each data type can represent a certain set of values, and each had a set of associated operations.
The traditional programming view is that data is passive – it ’ s manipulated and combined with active operations.
Introduction
• • Modern computer programs are built using an object-oriented approach.
Most applications you ’ re familiar with have Graphical User Interfaces (GUI) that provide windows, icons, buttons and menus.
Introduction
• • • • Python provides various options for developing graphical user interfaces (GUIs). Most important are listed below: Tkinter: Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would look this option in this tutorial.
wxPython: This is an open-source Python interface for wxWindows http://wxpython.org
.
JPython: JPython is a Python port for Java which gives Python scripts seamless access to Java class libraries on the local machine http://www.jython.org
.
Graphic User Interface
• • • Tkinter is the standard GUI library for Python.
Python when combined with Tkinter provides a fast and easy way to create GUI applications.
Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit.
Graphic User Interface
• • • • • Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following steps: Import the Tkinter module.
Create the GUI application main window.
Add one or more of the above-mentioned widgets to the GUI application.
Enter the main event loop to take action against each event triggered by the user.
Example1
• • • • #!/usr/bin/python import tkinter top = tkinter.Tk() # Code to add widgets will go here... top.mainloop()
Example2
• #!/usr/bin/python • import tkinter • top = tkinter.Tk() • • def helloCallBack(): tkinter.messagebox.showinfo( "Hello Python", "Hello World") • B = tkinter.Button(top, text ="Hello", command = helloCallBack) • B.pack() • top.mainloop()
Tkinter Widgets
• • • • Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI application. These controls are commonly called widgets.
There are currently 15 types of widgets in Tkinter. We present these widgets as well as a brief description in the following table:
Operator
Button Canvas Checkbutton Entry
Tkinter Widgets
Description
The Button widget is used to display buttons in your application.
The Canvas widget is used to draw shapes, such as lines, ovals, polygons and rectangles, in your application.
The Checkbutton widget is used to display a number of options as checkboxes. The user can select multiple options at a time.
The Entry widget is used to display a single-line text field for accepting values from a user.
Button
• • • The Button widget is used to add buttons in a Python application. These buttons can display text or images 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.
Syntax
• • • • • • Here is the simple syntax to create this widget: w = Button ( master, option=value, ... ) Parameters: master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
Button Example
• • Example2 shows the code for creating a Button and click it.
Canvas
• • • • • The Canvas is a rectangular area intended for drawing pictures or other complex layouts.
You can place graphics, text, widgets or frames on a Canvas.
Syntax Here is the simple syntax to create this widget: w = Canvas ( master, option=value, ... )
Parameters
• • • master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
Option
bd bg confine
Options
Description
Border width in pixels. Default is 2.
Normal background color.
If true (the default), the canvas cannot be scrolled outside of the scrollregion.
Example3
• import tkinter • top = tkinter.Tk() • C = tkinter.Canvas(top, bg="blue", height=250, width=300) • • coord = 10, 50, 240, 210 arc = C.create_arc(coord, start=0, extent=150, fill="red") • • C.pack() top.mainloop()
CheckButton
• • • The Checkbutton widget is used to display a number of options to a user as toggle buttons.
The user can then select one or more options by clicking the button corresponding to each option.
You can also display images in place of text.
CheckButton
• • • • • • Syntax Here is the simple syntax to create this widget: w = Checkbutton ( master, option, ... ) Parameters: master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
Option
activebackgroun d activeforeground bg bitmap bd ommand cursor disabledforegrou nd font
CheckButton
Description
Background color when the checkbutton is under the cursor.
Foreground color when the checkbutton is under the cursor.
The normal background color displayed behind the label and indicator.
To display a monochrome image on a button.
The size of the border around the indicator. Default is 2 pixels.
A procedure to be called every time the user changes the state of this checkbutton.
If you set this option to a cursor name (arrow, dot etc.), the mouse
cursor will change to that pattern when it is over the checkbutton.
The foreground color used to render the text of a disabled checkbutton. The default is a stippled version of the default foreground color.
The font used for the text.
CheckButton
• Following are commonly used methods for this widget:
Method
deselect() flash() invoke() select() toggle()
Description
Clears (turns off) the checkbutton.
Flashes the checkbutton a few times between its active and normal colors, but leaves it the way it started.
You can call this method to get the same actions that would occur if the user clicked on the checkbutton to change its state.
Sets (turns on) the checkbutton.
Clears the checkbutton if set, sets it if cleared.
Example4
• • • • • • • • • • • import tkinter top = tkinter.Tk() CheckVar1 = tkinter.IntVar() CheckVar2 = tkinter.IntVar() C1 = tkinter.Checkbutton(top, text = "Music", variable = CheckVar1, onvalue = 1, offvalue = 0, height=5, width = 20) C2 = tkinter.Checkbutton(top, text = "Video", variable = CheckVar2, onvalue = 1, offvalue = 0, height=5, width = 20) C1.pack() C2.pack() top.mainloop()
Entry
• • • The Entry widget is used to accept single-line text strings from a user.
If you want to display multiple lines of text that can be edited, then you should use the Text widget.
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.
Entry
• • • • • • Syntax Here is the simple syntax to create this widget: w = Entry( master, option, ... ) Parameters master: This represents the parent window.
options: Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
Option
bg bd command cursor font exportselection fg highlightcolor justify
Entry
Description
The normal background color displayed behind the label and indicator.
The size of the border around the indicator. Default is 2 pixels.
A procedure to be called every time the user changes the state of this checkbutton.
If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change to that pattern when it is over the checkbutton.
The font used for the text.
By default, if you select text within an Entry widget, it is automatically exported to the clipboard. To avoid this exportation, use exportselection=0.
The color used to render the text.
The color of the focus highlight when the checkbutton has the focus.
If the text contains multiple lines, this option controls how the text is justified: CENTER, LEFT, or RIGHT.
Entry
• • Methods The following are commonly used methods for this widget:
Entry
Medthod
delete ( first, last=None ) get() icursor ( index ) index ( index ) insert ( index, s ) select_adjust ( index )
Description
Deletes characters from the widget, starting with the one at index first, up to but not including the character at position last. If the second argument is omitted, only the single character at position first is deleted.
Returns the entry's current text as a string.
Set the insertion cursor just before the character at the given index.
Shift the contents of the entry so that the character at the given index is the leftmost visible character. Has no effect if the text fits entirely within the entry.
Inserts string s before the character at the given index.
This method is used to make sure that the selection includes the character at the specified index.
Example5
• • • • • • • • Try the following for yourself: from Tkinter import * top = Tk() L1 = Label(top, text="User Name") L1.pack( side = LEFT) E1 = Entry(top, bd =5) E1.pack(side = RIGHT) top.mainloop()
Event driven programming
• • • Graphical interfaces can be used for input as well as output.
In a GUI environment, users typically interact with their applications by clicking on buttons, choosing items from menus, and typing information into on-screen text boxes. These applications use technique called event- driven programming.
Event driven programming
• • • • Basically, the program draws a set of interface elements (often called widgets) on the screen, and then waits for the user to do something.
When the user moves the mouse, clicks a button, or types a key on a keyboard, his generates an event.
Basically, an event is an object that encapsulates data about what just happened.
The event object is then sent to an appropriate part of the program to be processed.
Events and Bindings
• • a Tkinter application spends most of its time inside an event loop (entered via the mainloop method). Events can come from various sources, including key presses and mouse operations by the user, and redraw events from the window manager (indirectly caused by the user, in many cases).
Events and Bindings
• • • • • Tkinter provides a powerful mechanism to let you deal with events yourself. For each widget, you can bind Python functions and methods to events.
widget.bind(event, handler) If an event matching the event description occurs in the widget, the given handler is called with an object describing the event.
Here is an example:
Getting Mouse Clicks
• • • • • • • • from tkinter import * top = Tk() def callback(event): print('You clicked at: ', event.x, event.y) frame = Frame(top, width=100, height=100) frame.bind("
Getting Mouse Click
• • • In this example, we use the bind method of the frame widget to bind a callback function to an event called
Getting Keyboard Events
• • • Keyboard events are sent to the widget that currently owns the keyboard focus. You can use the focus_set method to move focus to a widget: If you run this script, you’ll find that you have to click in the frame before it starts receiving any keyboard events.
Getting Keyboard Events
• • • • • • • • • • • • from tkinter import * top = Tk() def key(event): print ("pressed", repr(event.char)) def callback(event): frame.focus_set() print("clicked at", event.x, event.y) frame = Frame(top, width=100, height=100) frame.bind("
Events
• • • Events are given as strings, using a special event syntax:
Events
• • • The modifier and detail fields are used to give additional information, and can in many cases be left out. There are also various ways to simplify the event string; for example, to match a keyboard key, you can leave out the angle brackets and just use the key as is. Unless it is a space or an angle bracket, of course.
Event Formats
• • •
Event Formats
• • The current position of the mouse pointer (relative to the widget) is provided in the x and y members of the event object passed to the callback.
You can use ButtonPress instead of Button, or even leave it out completely:
Event Formats
• •
Events Formats
• • •
Event Formats
• • •
Event Formats
• • • •
a The user typed an “a”. Most printable characters can be used as is. The exceptions are space (
Creating GUI using class
• • • • • • • • • • • • • • • • • • • import tkinter as tk class Application(tk.Frame): def __init__(self, master=None): tk.Frame.__init__(self, master) self.pack() self.createWidgets() def createWidgets(self): self.hi_there = tk.Button(self) self.hi_there["text"] = "Hello World\n(click me)" self.hi_there["command"] = self.say_hi self.hi_there.pack(side="top") self.QUIT = tk.Button(self, text="QUIT", fg="red", command=root.destroy) self.QUIT.pack(side="bottom") def say_hi(self): print("hi there, everyone!") root = tk.Tk() app = Application(master=root) app.mainloop()