Download Title: Line Styles in Python

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Assignment No:
Title: Line Styles in Python
Problem Statement:
Theory:
Introduction:
Python is a powerful modern computer programming language. Python allows you to use
variables without declaring them (i.e., it determines types implicitly), and it relies on
indentation as a control structure. You are not forced to define classes in Python (unlike Java)
but you are free to do so when convenient. Python was developed by Guido van Rossum, and
it is free software.
With python, small project can be written quickly. But python also scales up nicely and can
be used for mission – critical, commercial applications.
1. Features of Python:
1. Simple: Python is a simple and minimalistic language. With python’s clear and simple
rules, python is closer to English.
2. It is Powerful.
3. Free and Open Source: Python is an example of a FLOSS (Free/Libré and Open
Source Software). In simple terms, you can freely distribute copies of this software,
read it's source code, make changes to it, use pieces of it in new free programs, and
that you know you can do these things.
4. High-level Language: When you write programs in Python, you never need to bother
about the low-level details such as managing the memory used by your program, etc
5. Portable: Due to its open-source nature, Python has been ported (i.e. changed to make
it work on) to many platforms. You can use Python on Linux, Windows, FreeBSD,
Macintosh, Solaris etc.
6. Interpreted: Python, does not need compilation to binary. Internally, Python converts
the source code into an intermediate form called bytecodes and then translates this
into the native language of computer and then runs it.
7. Object Oriented: Python supports procedure-oriented programming as well as objectoriented programming. In procedure-oriented languages, the program is built around
procedures or functions which are nothing but reusable pieces of programs. In objectoriented languages, the program is built around objects which combine data and
functionality.
2. Why Python?
Java v/s Python :
1. Python programs run slower than the Java codes, but python saves much time and
space. Python programs are 3-5 times smaller than java programs.
2. Python is dynamic typed language. Python programmers don't need to waste time in
declaring variable types as in java.
3. Python is much easier to learn than Java.
C++ v/s Python:
1. Comparison is same as that between Java and Python except the program length in
python is 5-10 times shorter than that in C++.
2. Python programmers can complete a task in 2 months that takes a year in C++.
3. Python commands:
3.1. Comment:
In a Python command, anything after a # symbol is a comment. For example:
print "Hello world" #this is silly
Comments are not part of the command, but rather intended as documentation for anyone
reading the code. Multiline comments are also possible, and are enclosed by triple
double-quote symbols:
"""This is an example of a long comment that goes on and on and on."""
3.2 Numbers and other data types
Python recognizes several different types of data. For instance, 23 and −75 are integers,
while 5.0 and −23.09 are floats or floating point numbers. The type float is (roughly) the
same as a real number in mathematics. The number 12345678901 is a long integer;
Python prints it with an “L” appended to the end. Usually the type of a piece of data is
determined implicitly.
3.2.1 The type function
To see the type of some data, use Python’s builtin type function:
>>> type(-75)
<type ’int’>
>>> type(5.0)
<type ’float’>
>>> type(12345678901)
<type ’long’>
Another useful data type is complex, used for complex numbers. For example:
>>> 2j
2j
>>> 2j-1
(-1+2j)
>>> complex(2,3)
(2+3j)
>>> type(-1+2j)
<type ’complex’>
Notice that Python uses j for the complex unit (such that j2 = −1) just as physicists do,
instead of the letter i preferred by mathematicians.
3.2.2 Strings
Other useful data types are strings (short for “character strings”); for example "Hello
World!". Strings are sequences of characters enclosed in single or double quotes:
>>> "This is a string"
’This is a string’
>>> ’This is a string, too’
’This is a string, too’
>>> type("This is a string")
<type ’str’>
Strings are an example of a sequence type.
3.2.3 The range function
The range function is often used to create lists of integers. It has three forms. In the
simplest form, range(n) produces a list of all numbers 0,1,2,...,n−1 starting with 0 and
ending with n−1. For instance,
>>> range(17)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
You can also specify an optional starting point and an increment, which may be negative.
For instance, we have
>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(-6,0)
[-6, -5, -4, -3, -2, -1]
>>> range(1,10,2)
[1, 3, 5, 7, 9]
>>> range(10,0,-2)
[10, 8, 6, 4, 2]
Note the use of a negative increment in the last example.
3.3 Operators
The common binary operators for arithmetic are + for addition, - for subtraction, * for
multi- plication, and / for division. As already mentioned, Python uses ** for
exponentiation. Integer division is performed so that the result is always another integer
(the integer quotient):
>>> 25/3
8
>>> 5/2
2
This is a wrinkle that you will always have to keep in mind when working with Python.
To get a more accurate answer, use the float type:
>>> 25.0/3
8.3333333333333339
>>> 5/2.0
2.5
3.4 Variables and assignment
An assignment statement in Python has the form variable = expression. This has the
following effect. First the expression on the right hand side is evaluated, then the result is
assigned to the variable. After the assignment, the variable becomes a name for the result.
The variable retains the same value until another value is assigned, in which case the
previous value is lost. Executing the assignment produces no output; its purpose it to
make the association between the variable and its value.
>>> x = 2+2
>>> print x
4
In the example above, the assignment statement sets x to 4, producing no output. If we
want to see the value of x, we must print it. If we execute another assignment to x, then
the previous value is lost.
>>> x = 380.5
>>> print x
380.5
>>> y = 2*x
>>> print y
761.0
Remember: A single = is used for assignment, the double == is used to test for equality.
In mathematics the equation x = x + 1 is nonsense; it has no solution. In computer
science, the statement x = x + 1 is useful. Its purpose is to add 1 to x, and reassign the
result to x. In short, x is incremented by 1.
>>> x = 10
>>> x = x + 1
>>> print x
11
>>> x = x + 1
>>> print x
12
3.6 Decisions
The if–else is used to make choices in Python code. This is a compound statement. The
simplest form is
if c o n d i t i o n :
a c t i o n −1
else:
a c t i o n −2
The indentation is required.
Note that the else and its action are optional. The actions action-1 and action-2 may
consist of many statements; they must all be indented the same amount. The condition is
an expression which evaluates to True or False. Of course, if the condition evaluates to
True then action-1 is executed, otherwise action-2 is exe- cuted. In either case execution
continues with the statement after the if-else. For example, the code
x=1
if x > 0:
print "Friday is wonderful"
else:
print "Monday sucks"
print "Have a good weekend"
Results in the output
Friday is wonderful Have a good weekend
Note that the last print statement is not part of the if-else statement (because it isn’t
indented), so if we change the first line to say x = 0 then the output would be
Monday sucks Have a good weekend
More complex decisions may have several alternatives depending on several conditions.
For these the elif is used. It means “else if” and one can have any number of elif clauses
between the if and the else. The usage of elif is best illustrated by an example:
if x >= 0 and x < 10:
digits = 1
elif x >= 10 and x < 100:
digits = 2
elif x >= 100 and x < 1000:
digits = 3
elif x >= 1000 and x < 10000:
digits = 4
else:
digits = 0 # more than 4
In the above, the number of digits in x is computed, so long as the number is 4 or less. If x
is negative or greater than 10000, then digits will be set to zero.
3.7 Loops
Python provides two looping commands: for and while. These are compound commands.
3.7.1 for loop
The syntax of a for loop is
for item in l i s t :
action
As usual, the action consists of one or more statements, all at the same indentation level.
These statements are also known as the body of the loop. The item is a variable name, and
list is a list. Execution of the for loop works by setting the variable successively to each
item in the list, and then executing the body each time. Here is a simple example (the
comma at the end of the print makes all printing occur on the same line):
for i in [2, 4, 6, 0]:
print i,
This produces the output
2460
3.7.2 while loop
The syntax of the while loop is
while c o n d i t i o n :
action
Of course, the action may consist of one or more statements all at the same indentation
level. The statements in the action are known as the body of the loop. Execution of the
loop works as follows. First the condition is evaluated. If True, the body is executed and
the condition evaluated again, and this repeats until the condition evaluates to False. Here
is a simple example:
n=0
while n < 10:
print n,
n=n+3
This produces the following output
0369
Note that the body of a while loop is never executed if the condition evaluates to False the
first time. Also, if the body does not change the subsequent evaluations of the condition,
an infinite loop may occur. For example
while True:
print "Hello",
will print Hellos endlessly. To interrupt the execution of an infinite loop, use CTRL-C.
4. GUI Programming in Python
Python has a huge number of GUI frameworks (or toolkits) available for it. The major
cross-platform technologies upon which Python frameworks are based include Gtk, Qt, Tk
and wxWidgets, although many other technologies provide actively maintained Python
bindings.
Some of Python frameworks are
1. JPython: Jython is an implementation of the high-level, dynamic, object-oriented
language Python seamlessly integrated with the Java platform. It can be fully
integrated into existing Java applications; alternatively, Python applications can be
compiled into a collection of Java classes. Python programs running on the Jython
virtual machine have full access to the Java classes and APIs.
2. PyQt: PyQt is a Python binding of the cross-platform GUI toolkit Qt. It is one of
Python's options for GUI programming. PyQt is free software. PyQt is implemented as
a Python plug-in.
3. PyGTK: PyGTK is a set of Python wrappers for the GTK+ graphical user
interface library. PyGTK is free software.
4. PyCairo:
5. Tkinter: Tkinter is a Python binding to the Tk GUI toolkit. It is the standard Python
interface to the Tk GUI toolkit and is Python's de facto standard GUI, and is included
with the standard Windows and Mac OS X install of Python. The name Tkinter comes
from Tk interface. Tkinter is implemented as a Python wrapper around a
complete Tcl interpreter embedded in the Python interpreter. Tkinter calls are
translated into Tcl commands which are fed to this embedded interpreter, thus making
it possible to mix Python and Tcl in a single application.
Tkinter Programming
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.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the
following steps:
a)
b)
c)
d)
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.
Example
#!/usr/bin/python
import Tkinter
top = Tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()
This would create a following window:
kinter 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
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.
Frame
The Frame widget is used as a container widget to organize other
widgets.
Label
The Label widget is used to provide a single-line caption for other
widgets. It can also contain images.
Listbox
The Listbox widget is used to provide a list of options to a user.
Menubutton
The Menubutton widget is used to display menus in your application.
Menu
The Menu widget is used to provide various commands to a user.
These commands are contained inside Menubutton.
Message
The Message widget is used to display multiline text fields for
accepting values from a user.
Radiobutton
The Radiobutton widget is used to display a number of options as
radio buttons. The user can select only one option at a time.
Scale
The Scale widget is used to provide a slider widget.
Scrollbar
The Scrollbar widget is used to add scrolling capability to various
widgets, such as list boxes.
Text
The Text widget is used to display text in multiple lines.
Toplevel
The Toplevel widget is used to provide a separate window container.
Spinbox
The Spinbox widget is a variant of the standard Tkinter Entry
widget, which can be used to select from a fixed number of values.
PanedWindow
A PanedWindow is a container widget that may contain any number
of panes, arranged horizontally or vertically.
LabelFrame
A labelframe is a simple container widget. Its primary purpose is to
act as a spacer or container for complex window layouts.
tkMessageBox This module is used to display message boxes in your applications.
Geometry Management in Tkinter:
All Tkinter widgets have access to specific geometry management methods, which have the
purpose of organizing widgets throughout the parent widget area. Tkinter exposes the
following geometry manager classes: pack, grid, and place.



The pack() Method - This geometry manager organizes widgets in blocks before placing
them in the parent widget.
The grid() Method - This geometry manager organizes widgets in a table-like structure in the
parent widget.
The place() Method -This geometry manager organizes widgets by placing them in a specific
position in the parent widget.
The Canvas Widget:
The canvas widget provides the basic graphics facilities for Tkinter, and so more advanced
functions. Drawing on the canvas is done by creating various items on it.
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
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.
Cursor
Cursor used in the canvas like arrow, circle, dot etc.
Height
Size of the canvas in the Y dimension.
highlightcolor
Color shown in the focus highlight.
Relief
Relief specifies the type of the border. Some of the values are
SUNKEN, RAISED, GROOVE, and RIDGE.
Scrollregion
A tuple (w, n, e, s) that defines over how large an area the canvas
can be scrolled, where w is the left side, n the top, e the right side,
and s the bottom.
Width
Size of the canvas in the X dimension.
If you set this option to some positive dimension, the canvas can be
positioned only on multiples of that distance, and the value will be
xscrollincrement
used for scrolling by scrolling units, such as when the user clicks
on the arrows at the ends of a scrollbar.
xscrollcommand
If the canvas is scrollable, this attribute should be the .set() method
of the horizontal scrollbar.
yscrollincrement Works like xscrollincrement, but governs vertical movement.
yscrollcommand
If the canvas is scrollable, this attribute should be the .set() method
of the vertical scrollbar.
The Canvas widget can support the following standard items:
arc . Creates an arc item, which can be a chord, a pieslice or a simple arc.
coord = 10, 50, 240, 210
arc = canvas.create_arc(coord, start=0, extent=150, fill="blue")
image . Creates an image item, which can be an instance of either the BitmapImage or the
PhotoImage classes.
filename = PhotoImage(file = "sunshine.gif")
image = canvas.create_image(50, 50, anchor=NE, image=filename)
line . Creates a line item.
id = canvas.create_line(x0, y0, x1, y1, ..., xn, yn, option, ...)
The line goes through the series of points (x0, y0), (x1, y1), … (xn, yn).
Some Canvas line options are:
a) activedash, activefill, activestipple, activewidth : These options specify
the dash, fill, stipple, and width values to be used when the line is active, that is, when
the mouse is over it.
b) Arrow: The default is for the line to have no arrowheads. Use arrow=tk.FIRST to get
an arrowhead at the (x0, y0) end of the line. Use arrow=tk.LAST to get an arrowhead
at the far end. Usearrow=tk.BOTH for arrowheads at both ends.
c) Dash: This option is specified as a tuple of integers. The first integer specifies how
many pixels should be drawn. The second integer specifies how many pixels should
be skipped before starting to draw again, and so on. When all the integers in the tuple
are exhausted, they are reused in the same order until the border is complete.
For example, dash=(3,5) produces alternating 3-pixel dashes separated by 5-pixel
gaps. A value of dash=(7,1,1,1) produces a dash-and-dot pattern, with the dash seven
times as long as the dot or the gaps around the dot. A value of dash=(5,) produces
alternating five-pixel dashes and five-pixel gaps.
d) dashoffset: To start the dash pattern in a different point of cycle instead of at the
beginning, use an option of dashoff=n, where n is the number of pixels to skip at the
beginning of the pattern.
e) fill : The color to use in drawing the line. Default is fill='black'.
f) width: The line's width. Default is 1 pixel.
oval . Creates a circle or an ellipse at the given coordinates. It takes two pairs of coordinates;
the top left and bottom right corners of the bounding rectangle for the oval.
oval = canvas.create_oval(x0, y0, x1, y1, options)
polygon . Creates a polygon item that must have at least three vertices.
polygon = canvas.create_polygon(x0, y0, x1, y1,...xn, yn, options)
Example:
Try the following example yourself:
import Tkinter
import tkMessageBox
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()
When the above code is executed, it produces the following result: