WEEK 12-13 - State University of Zanzibar
Download
Report
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:
Tkinter Widgets
Operator
Description
Button
The Button widget is used to display buttons in your application.
Canvas
The Canvas widget is used to draw shapes, such as lines, ovals,
polygons and rectangles, in your application.
Checkbutton
The Checkbutton widget is used to display a number of options
as checkboxes. The user can select multiple options at a time.
Entry
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.
Options
Option
Description
bd
Border width in pixels. Default is 2.
bg
Normal background color.
confine
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.
CheckButton
Option
Description
activebackgroun
d
Background color when the checkbutton is under the cursor.
activeforeground
Foreground color when the checkbutton is under the cursor.
bg
The normal background color displayed behind the label and
indicator.
bitmap
To display a monochrome image on a button.
bd
The size of the border around the indicator. Default is 2 pixels.
ommand
A procedure to be called every time the user changes the state of
this checkbutton.
cursor
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.
disabledforegrou
nd
The foreground color used to render the text of a disabled
checkbutton. The default is a stippled version of the default
foreground color.
font
The font used for the text.
CheckButton
• Following are commonly used methods for
this widget:
Method
Description
deselect()
Clears (turns off) the checkbutton.
flash()
Flashes the checkbutton a few times between its active and
normal colors, but leaves it the way it started.
invoke()
You can call this method to get the same actions that would
occur if the user clicked on the checkbutton to change its
state.
select()
Sets (turns on) the checkbutton.
toggle()
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.
Entry
Option
Description
bg
The normal background color displayed behind the label and
indicator.
bd
The size of the border around the indicator. Default is 2 pixels.
command
A procedure to be called every time the user changes the state of
this checkbutton.
cursor
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.
font
The font used for the text.
exportselection
By default, if you select text within an Entry widget, it is
automatically exported to the clipboard. To avoid this exportation,
use exportselection=0.
fg
The color used to render the text.
highlightcolor
The color of the focus highlight when the checkbutton has the focus.
justify
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
Description
delete ( first,
last=None )
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.
get()
Returns the entry's current text as a string.
icursor ( index )
Set the insertion cursor just before the character at the given
index.
index ( 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.
insert ( index, s )
Inserts string s before the character at the given index.
select_adjust ( 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 eventdriven 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("<Button-1>", callback)
frame.pack()
top.mainloop()
Getting Mouse Click
• In this example, we use the bind method of
the frame widget to bind a callback function
to an event called <Button-1>.
• Run this program and click in the window that
appears.
• Each time you click, a message like “clicked at
44 63” is printed to the console window.
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("<Key>", key)
frame.bind("<Button-1>", callback)
frame.pack()
top.mainloop()
Events
• Events are given as strings, using a special
event syntax:
• <modifier-type-detail> The type field is the
most important part of an event specifier.
• It specifies the kind of event that we wish to
bind, and can be user actions like Button, and
Key, or window manager events like Enter,
Configure, and others.
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
• <Button-1> A mouse button is pressed over the
widget.
• Button 1 is the leftmost button, button 2 is the middle
button (where available), and button 3 the rightmost
button.
• When you press down a mouse button over a widget,
Tkinter will automatically “grab” the mouse pointer,
and subsequent mouse events (e.g. Motion and
Release events) will then be sent to the current widget
as long as the mouse button is held down, even if the
mouse is moved outside the current widget.
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: <Button-1>,
<ButtonPress-1>, and <1> are all synonyms.
For clarity, I prefer the <Button-1> syntax.
Event Formats
• <B1-Motion> The mouse is moved, with mouse
button 1 being held down (use B2 for the middle
button, B3 for the right button). The current
position of the mouse pointer is provided in the x
and y members of the event object passed to the
callback.
• <ButtonRelease-1> Button 1 was released. The
current position of the mouse pointer is provided
in the x and y members of the event object
passed to the callback.
Events Formats
• <Double-Button-1> Button 1 was double
clicked. You can use Double or Triple as
prefixes. Note that if you bind to both a single
click (<Button-1>) and a double click, both
bindings will be called.
• <Enter> The mouse pointer entered the
widget (this event doesn’t mean that the user
pressed the Enter key!).
• <Leave> The mouse pointer left the widget.
Event Formats
• <FocusIn> Keyboard focus was moved to this widget, or to
a child of this widget.
• <FocusOut> Keyboard focus was moved from this widget to
another widget.
• <Return> The user pressed the Enter key. You can bind to
virtually all keys on the keyboard. For an ordinary 102-key
PC-style keyboard, the special keys are Cancel (the Break
key), BackSpace, Tab, Return(the Enter key), Shift_L (any
Shift key), Control_L (any Control key), Alt_L (any Alt key),
Pause, Caps_Lock, Escape, Prior (Page Up), Next (Page
Down), End, Home, Left, Up, Right, Down, Print, Insert,
Delete, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12,
Num_Lock, and Scroll_Lock.
Event Formats
• <Key> The user pressed any key. The key is provided in the
char member of the event object passed to the callback
(this is an empty string for special keys).
• a The user typed an “a”. Most printable characters can be
used as is. The exceptions are space (<space>) and less
than (<less>). Note that 1 is a keyboard binding, while <1>
is a button binding.
• <Shift-Up> The user pressed the Up arrow, while holding
the Shift key pressed. You can use prefixes like Alt, Shift,
and Control.
• <Configure> The widget changed size (or location, on some
platforms). The new size is provided in the width and
height attributes of the event object passed to the callback.
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()