Hello all. My name is Younis, I am a computer science newb. I occasionally browse this website reading some fascinating threads. I have a simple project at hand which i am finding the extra credit portion to be somewhat difficult.

The project is very simple,
the project takes a number from the user and
- if the number is one, it quits
-if the number is even, we cut it in half
-if the number is odd, multiply is by 3 and add 1

so if we look at the number 13 it goes like this:
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1

so the length of the chain would be 10.

So our job is to print a menu to the user.
If the user enters "I", ask the user for a number, print the chain and length of the chain for that number

if the user enters "R", ask the user for a range of numbers, and print the length and chain of each number

If the user enters "L", ask the user for a range of numbers, and print the number with the longest chain length.

If the user enters "Q", then quit.

I have all of that working. now i the extra credit says:
if the user enters a number, and the next 10 numbers after that and draw a histograms.

so the x axis would be each of the number, and the y axis would be the chain length of that number.

I can get the number and length of each number in a list. but i am a newb as to how to draw this.
so if the user entered 2, we would draw a histogram of 2-11 and each bar of the number would reach up to the chain length of that number.

here is my code:

# Filename:    hw6.py
# Date:        10/16/09
# Section #:   06
# Description:
# This file contains python code for hailstone sequence.
# It follows the rules, if a number is even, it will divide the
# next number by two, if the number is odd, it will multiply the next
# number by three and then add 1. This will continuie forming a chain
# until the last number is 1.

# this function prints the chain of numbers using the rules
# also adds up the length chain
# Inputs : n
# Outputs : none

import string
# from graphics import *
from graphics import *

#Constant
MAX = 10000

# printing functions

# this function prints a brief description of the program to the user
# Inputs: none
# Outputs : none
def printGreeting():
print ""
print " This program finds hailstones sequences of numbers"
print " you choose. The next number in the sequence if found by"
print " either dividing it by two(if even) or multiplying by 3"
print " and adding 1(if odd).The program quits when the last"
print " number in the sequence is 1\n"

# this functions prints the menu for the user
# Inputs: none
# Outputs : none
print "\n\tI - view squence for an individual value\n"
print "\tR - veiw sequence for range of values\n"
print "\tL - Find the longest chain\n"
print "\tH - Print out the histogram\n"
print "\tQ - Quit\n\n"

# end of printing funtions

# hailstone(number) prints the hailstone sequence
# Inputs: number
# Outputs: none
def hailstone(n):

length = 1
print n,
# checks if n is not sential
while n != 1:

# if even, divide by 2 (rule). add 1 to length
if n % 2 == 0:
n = n / 2
print "->",n,
length = length + 1

# if odd, multiply by 3, add 1 (rule). add 1 to length
elif n % 2 != 0:
n = ( 3 * n ) + 1
print "->",n,
length = length + 1

# print the length at the end of each chain
print "; length =",length
print "----------------------------------------------------------------",
print "--------------\n"
return length

# this function returns the length of each chain from the starting number, n
# Inputs : n
# Outputs : none
def chain(n):

length = 1
while n != 1:

# if even, divide by 2 (rule). add 1 to length
if n % 2 == 0:
n = n / 2
length  = length + 1

# if even, divide by 2 (rule). add 1 to length
elif n % 2 != 0:
n = ( 3 * n ) + 1
length = length + 1
return length

# getValidInt() prompts the user to enter an integer in the specified range,
# rejects values not in that range by requiring new input, and only returns
# a valid integer.
# Inputs: the question of the prompt,
#         the minimum value in the range
#         and the maximum value in the range
# Output: an integer in the specified range
def getValidInt(question, min, max):

# use a bad value to enter the loop
value = max + 1

# compose the prompt
prompt = question + " (" + str(min) + "-" + str(max) + "): "

# continue to get values until the user enters a valid one
while value == "" or value < min or value > max:
value = raw_input(prompt)
if len(value) != 0:
value = int(value)

# return a valid value
return value

# this function finds the longest chain
# Inputs: none
# Outputs : none
def longChain():
begin = "Please enter the begining integer for the range"
end = "Please enter the ending integer for the range"

# calls to getValidInt for starting and ending values
beginNum = getValidInt(begin, 1, MAX)
endNum = getValidInt(end, beginNum + 1, MAX)

largestChain = beginNum

for i in range(beginNum, endNum+1):
if largestChain <= chain(i):
largestChain = i
length = chain(i)

print largestChain, " had the longest chain ", length

# this function finds the longest chain***************************8
# Inputs: none*************
# Outputs : none
def histogram():
# initialize variables
longestLength = 1
list = []

start = input("Please enter the begining integer for the range: ")
for n in range (start, start + 10):
length = chain(n)
list.append(length)
if longestLength <= chain(n):
longestLength = n
length = chain(n)
print longestLength
print list

def main():

# prints the greeting to the user
printGreeting()

# prints the menu to the user

# checks to see if choice entered is from the menu
while choice != 'Q':

# if choice is "I" or "i", proceeds to follow the individual steps
if choice == 'I':
hailstone(n)

# if choice is "R" or "r", proceds print each number and its sequence
# until the last number is 1, uses getValidInt to get valid integers
# for the function
elif choice == 'R':

begin = "Please enter the begining integer for the range"
end = "Please enter the ending integer for the range"

# calls to getValidInt for starting and ending values
beginNum = getValidInt(begin, 1, MAX)
endNum = getValidInt(end, beginNum + 1, MAX)

# for loop to get the values between starting and ending value
for n in range(beginNum,endNum+1):

#call to the hailstone function
hailstone(n)

# if choice is "L" or "l", proceeds to use getValidInt again to get the
# range, error checks on the range, and then calls the function chain
# to determine the length.
elif choice == 'L':
# call to function longchain
longChain()

elif choice == 'H':
histogram()

# if niether of the menu choices, then it prints that the
# entered text is not a valid choices
else:
print choice, "is not a valid choice"

# prints the menu to the user

main()

## All 6 Replies

i also have this graphics.py which the professor gave us. It has a bunch of the drawing codes in it.

Normally I'd suggest to use something like mathplotlib, but since he gave you graphics.py, he probably wants you to use it to draw the histograms. Could you attach it to your post?

Normally I'd suggest to use something like mathplotlib, but since he gave you graphics.py, he probably wants you to use it to draw the histograms. Could you attach it to your post?

does that mean like give u the code? its very long? like past it here? sorry new to this.

Yes, you can paste it here, or you can attach it as a file to one of your posts.

Yes, you can paste it here, or you can attach it as a file to one of your posts.

here is the code.. THANKS.

# graphics.py
"""Simple object oriented graphics library

The library is designed to make it very easy for novice programmers to
experiment with computer graphics in an object oriented fashion. It is
written by John Zelle for use with the book "Python Programming: An
Introduction to Computer Science" (Franklin, Beedle & Associates).

LICENSE: This is open-source software released under the terms of the

PLATFORMS: The package is a wrapper around Tkinter and should run on
any platform where Tkinter is available.

INSTALLATION: Put this file somewhere where Python can see it.

OVERVIEW: There are two kinds of objects in the library. The GraphWin
class implements a window where drawing can be done and various
GraphicsObjects are provided that can be drawn into a GraphWin. As a
simple example, here is a complete program to draw a circle of radius
10 centered in a 100x100 window:

--------------------------------------------------------------------
from graphics import *

def main():
win = GraphWin("My Circle", 100, 100)
c = Circle(Point(50,50), 10)
c.draw(win)
win.getMouse() // Pause to view result

main()
--------------------------------------------------------------------
GraphWin objects support coordinate transformation through the
setCoords method and pointer-based input through getMouse.

The library provides the following graphical objects:
Point
Line
Circle
Oval
Rectangle
Polygon
Text
Entry (for text-based input)
Image

Various attributes of graphical objects can be set such as
outline-color, fill-color and line-width. Graphical objects also
support moving and hiding for animation effects.

The library also provides a very simple class for pixel-based image
manipulation, Pixmap. A pixmap can be loaded from a file and displayed
using an Image object. Both getPixel and setPixel methods are provided
for manipulating the image.

DOCUMENTATION: For complete documentation, see Chapter 5 of "Python
Programming: An Introduction to Computer Science" by John Zelle,
http://mcsp.wartburg.edu/zelle/python for a quick reference"""

# Version 3.4 10/16/07
#     Fixed GraphicsError to avoid "exploded" error messages.
# Version 3.3 8/8/06
#     Added checkMouse method to GraphWin
# Version 3.2.2 5/30/05
#     Cleaned up handling of exceptions in Tk thread. The graphics package
#     now raises an exception if attempt is made to communicate with
# Version 3.2.1 5/22/05
#        error "chatter" when main thread terminates
#     Renamed various private globals with _
# Version 3.2 5/4/05
#     Added Pixmap object for simple image manipulation.
# Version 3.1 4/13/05
#     Improved the Tk thread communication so that most Tk calls
#        do not have to wait for synchonization with the Tk thread.
#        (see _tkCall and _tkExec)
# Version 3.0 12/30/04
#     Implemented Tk event loop in separate thread. Should now work
#        interactively with IDLE. Undocumented autoflush feature is
#        no longer necessary. Its default is now False (off). It may
#        be removed in a future version.
#     Better handling of errors regarding operations on windows that
#       have been closed.
#     Addition of an isClosed method to GraphWindow class.

# Version 2.2 8/26/04
#     Fixed cloning bug reported by Joseph Oldham.
#     Now implements deep copy of config info.
# Version 2.1 1/15/04
#        the window are done after each action. This makes some graphics
#        intensive programs sluggish. Turning off autoflush causes updates
#        to happen during idle periods or when flush is called.
# Version 2.0
#     Updated Documentation
#     Made Polygon accept a list of Points in constructor
#     Made all drawing functions call TK update for easier animations
#          and to make the overall package work better with
#          Python 2.3 and IDLE 1.0 under Windows (still some issues).
#     Removed vestigial turtle graphics.
#     Added ability to configure font for Entry objects (analogous to Text)
#     Added setTextColor for Text as an alias of setFill
#     Changed to class-style exceptions
#     Fixed cloning of Text objects

# Version 1.6
#     Fixed Entry so StringVar uses _root as master, solves weird
#            interaction with shell in Idle
#     Fixed bug in setCoords. X and Y coordinates can increase in
#           "non-intuitive" direction.
#     Tweaked wm_protocol so window is not resizable and kill box closes.

# Version 1.5
#     Fixed bug in Entry. Can now define entry before creating a
#     GraphWin. All GraphWins are now toplevel windows and share
#     a fixed root (called _root).

# Version 1.4
#     Fixed Garbage collection of Tkinter images bug.
#     Added ability to set text atttributes.

import time, os, sys
import Tkinter
tk = Tkinter

##########################################################################
# Module Exceptions

import exceptions

class GraphicsError(exceptions.Exception):
"""Generic error class for graphics module exceptions."""
#def __init__(self, *args):
#self.args=args

pass

UNSUPPORTED_METHOD = "Object doesn't support operation"

###########################################################################
# Support to run Tk in a separate thread

from copy import copy
from Queue import Queue
import atexit

_tk_request = Queue(0)
_tk_result = Queue(1)
_POLL_INTERVAL = 10

_root = None
_exception_info = None

global _root
_root = tk.Tk()
_root.withdraw()
_root.after(_POLL_INTERVAL, _tk_pump)
_root.mainloop()

def _tk_pump():
while not _tk_request.empty():
command,returns_value = _tk_request.get()
try:
result = command()
if returns_value:
_tk_result.put(result)
except:
if returns_value:
_tk_result.put(None) # release client
raise # re-raise the exception -- kills the thread
_root.after(_POLL_INTERVAL, _tk_pump)

def _tkCall(f, *args, **kw):
# execute synchronous call to f in the Tk thread
# this function should be used when a return value from
#   f is required or when synchronizing the threads.
def func():
return f(*args, **kw)
_tk_request.put((func,True),True)
result = _tk_result.get(True)
return result

def _tkExec(f, *args, **kw):
# schedule f to execute in the Tk thread. This function does
#   not wait for f to actually be executed.
#global _exception_info
#_exception_info = None
def func():
return f(*args, **kw)
_tk_request.put((func,False),True)
#if _exception_info is not None:
#    raise GraphicsError, "Invalid Operation: %s" % str(_exception_info)

def _tkShutdown():
#_tkExec(sys.exit)
time.sleep(.5) # give tk thread time to quit

# Fire up the separate Tk thread

# Kill the tk thread at exit
atexit.register(_tkShutdown)

############################################################################
# Graphics classes start here

class GraphWin(tk.Canvas):

"""A GraphWin is a toplevel window for displaying graphics."""

def __init__(self, title="Graphics Window",
width=200, height=200, autoflush=False):
_tkCall(self.__init_help, title, width, height, autoflush)

def __init_help(self, title, width, height, autoflush):
master = tk.Toplevel(_root)
master.protocol("WM_DELETE_WINDOW", self.__close_help)
tk.Canvas.__init__(self, master, width=width, height=height)
self.master.title(title)
self.pack()
master.resizable(0,0)
self.foreground = "black"
self.items = []
self.mouseX = None
self.mouseY = None
self.bind("<Button-1>", self._onClick)
self.height = height
self.width = width
self.autoflush = autoflush
self._mouseCallback = None
self.trans = None
self.closed = False
master.lift()
if autoflush: _root.update()

def __checkOpen(self):
if self.closed:
raise GraphicsError, "window is closed"

def setBackground(self, color):
"""Set background color of the window"""
self.__checkOpen()
_tkExec(self.config, bg=color)
#self.config(bg=color)

def setCoords(self, x1, y1, x2, y2):
"""Set coordinates of window to run from (x1,y1) in the
lower-left corner to (x2,y2) in the upper-right corner."""
self.trans = Transform(self.width, self.height, x1, y1, x2, y2)

def close(self):
if self.closed: return
_tkCall(self.__close_help)

def __close_help(self):
"""Close the window"""
self.closed = True
self.master.destroy()
_root.update()

def isClosed(self):
return self.closed

def __autoflush(self):
if self.autoflush:
_tkCall(_root.update)

def plot(self, x, y, color="black"):
"""Set pixel (x,y) to the given color"""
self.__checkOpen()
xs,ys = self.toScreen(x,y)
#self.create_line(xs,ys,xs+1,ys, fill=color)
_tkExec(self.create_line,xs,ys,xs+1,ys,fill=color)
self.__autoflush()

def plotPixel(self, x, y, color="black"):
"""Set pixel raw (independent of window coordinates) pixel
(x,y) to color"""
self.__checkOpen()
#self.create_line(x,y,x+1,y, fill=color)
_tkExec(self.create_line, x,y,x+1,y, fill=color)
self.__autoflush()

def flush(self):
"""Update drawing to the window"""
self.__checkOpen()

def getMouse(self):
"""Wait for mouse click and return Point object representing
the click"""
self.mouseX = None
self.mouseY = None
while self.mouseX == None or self.mouseY == None:
#self.update()
_tkCall(self.update)
if self.isClosed(): raise GraphicsError, "getMouse in closed window"
x,y = self.toWorld(self.mouseX, self.mouseY)
self.mouseX = None
self.mouseY = None
return Point(x,y)

def checkMouse(self):
"""Return last mouse click or None if mouse has
not been clicked since last call"""
if self.isClosed():
raise GraphicsError, "checkMouse in closed window"
_tkCall(self.update)
if self.mouseX != None and self.mouseY != None:
x,y = self.toWorld(self.mouseX, self.mouseY)
self.mouseX = None
self.mouseY = None
return Point(x,y)
else:
return None

def getHeight(self):
"""Return the height of the window"""
return self.height

def getWidth(self):
"""Return the width of the window"""
return self.width

def toScreen(self, x, y):
trans = self.trans
if trans:
return self.trans.screen(x,y)
else:
return x,y

def toWorld(self, x, y):
trans = self.trans
if trans:
return self.trans.world(x,y)
else:
return x,y

def setMouseHandler(self, func):
self._mouseCallback = func

def _onClick(self, e):
self.mouseX = e.x
self.mouseY = e.y
if self._mouseCallback:
self._mouseCallback(Point(e.x, e.y))

class Transform:

"""Internal class for 2-D coordinate transformations"""

def __init__(self, w, h, xlow, ylow, xhigh, yhigh):
# w, h are width and height of window
# (xlow,ylow) coordinates of lower-left [raw (0,h-1)]
# (xhigh,yhigh) coordinates of upper-right [raw (w-1,0)]
xspan = (xhigh-xlow)
yspan = (yhigh-ylow)
self.xbase = xlow
self.ybase = yhigh
self.xscale = xspan/float(w-1)
self.yscale = yspan/float(h-1)

def screen(self,x,y):
# Returns x,y in screen (actually window) coordinates
xs = (x-self.xbase) / self.xscale
ys = (self.ybase-y) / self.yscale
return int(xs+0.5),int(ys+0.5)

def world(self,xs,ys):
# Returns xs,ys in world coordinates
x = xs*self.xscale + self.xbase
y = self.ybase - ys*self.yscale
return x,y

# Default values for various item configuration options. Only a subset of
#   keys may be present in the configuration dictionary for a given item
DEFAULT_CONFIG = {"fill":"",
"outline":"black",
"width":"1",
"arrow":"none",
"text":"",
"justify":"center",
"font": ("helvetica", 12, "normal")}

class GraphicsObject:

"""Generic base class for all of the drawable objects"""
# A subclass of GraphicsObject should override _draw and
#   and _move methods.

def __init__(self, options):
# options is a list of strings indicating which options are
# legal for this object.

# When an object is drawn, canvas is set to the GraphWin(canvas)
#    object where it is drawn and id is the TK identifier of the
#    drawn shape.
self.canvas = None
self.id = None

# config is the dictionary of configuration options for the widget.
config = {}
for option in options:
config[option] = DEFAULT_CONFIG[option]
self.config = config

def setFill(self, color):
"""Set interior color to color"""
self._reconfig("fill", color)

def setOutline(self, color):
"""Set outline color to color"""
self._reconfig("outline", color)

def setWidth(self, width):
"""Set line weight to width"""
self._reconfig("width", width)

def draw(self, graphwin):

"""Draw the object in graphwin, which should be a GraphWin
object.  A GraphicsObject may only be drawn into one
window. Raises an error if attempt made to draw an object that

if self.canvas and not self.canvas.isClosed(): raise GraphicsError, OBJ_ALREADY_DRAWN
if graphwin.isClosed(): raise GraphicsError, "Can't draw to closed window"
self.canvas = graphwin
#self.id = self._draw(graphwin, self.config)
self.id = _tkCall(self._draw, graphwin, self.config)
if graphwin.autoflush:
#_root.update()
_tkCall(_root.update)

def undraw(self):

"""Undraw the object (i.e. hide it). Returns silently if the
object is not currently drawn."""

if not self.canvas: return
if not self.canvas.isClosed():
#self.canvas.delete(self.id)
_tkExec(self.canvas.delete, self.id)
if self.canvas.autoflush:
#_root.update()
_tkCall(_root.update)
self.canvas = None
self.id = None

def move(self, dx, dy):

"""move object dx units in x direction and dy units in y
direction"""

self._move(dx,dy)
canvas = self.canvas
if canvas and not canvas.isClosed():
trans = canvas.trans
if trans:
x = dx/ trans.xscale
y = -dy / trans.yscale
else:
x = dx
y = dy
#self.canvas.move(self.id, x, y)
_tkExec(self.canvas.move, self.id, x, y)
if canvas.autoflush:
#_root.update()
_tkCall(_root.update)

def _reconfig(self, option, setting):
# Internal method for changing configuration of the object
# Raises an error if the option does not exist in the config
#    dictionary for this object
if not self.config.has_key(option):
raise GraphicsError, UNSUPPORTED_METHOD
options = self.config
options[option] = setting
if self.canvas and not self.canvas.isClosed():
#self.canvas.itemconfig(self.id, options)
_tkExec(self.canvas.itemconfig, self.id, options)
if self.canvas.autoflush:
#_root.update()
_tkCall(_root.update)

def _draw(self, canvas, options):
"""draws appropriate figure on canvas with options provided
Returns Tk id of item drawn"""
pass # must override in subclass

def _move(self, dx, dy):
"""updates internal state of object to move it dx,dy units"""
pass # must override in subclass

class Point(GraphicsObject):
def __init__(self, x, y):
GraphicsObject.__init__(self, ["outline", "fill"])
self.setFill = self.setOutline
self.x = x
self.y = y

def _draw(self, canvas, options):
x,y = canvas.toScreen(self.x,self.y)
return canvas.create_rectangle(x,y,x+1,y+1,options)

def _move(self, dx, dy):
self.x = self.x + dx
self.y = self.y + dy

def clone(self):
other = Point(self.x,self.y)
other.config = self.config.copy()
return other

def getX(self): return self.x
def getY(self): return self.y

class _BBox(GraphicsObject):
# Internal base class for objects represented by bounding box
# (opposite corners) Line segment is a degenerate case.

def __init__(self, p1, p2, options=["outline","width","fill"]):
GraphicsObject.__init__(self, options)
self.p1 = p1.clone()
self.p2 = p2.clone()

def _move(self, dx, dy):
self.p1.x = self.p1.x + dx
self.p1.y = self.p1.y + dy
self.p2.x = self.p2.x + dx
self.p2.y = self.p2.y  + dy

def getP1(self): return self.p1.clone()

def getP2(self): return self.p2.clone()

def getCenter(self):
p1 = self.p1
p2 = self.p2
return Point((p1.x+p2.x)/2.0, (p1.y+p2.y)/2.0)

class Rectangle(_BBox):

def __init__(self, p1, p2):
_BBox.__init__(self, p1, p2)

def _draw(self, canvas, options):
p1 = self.p1
p2 = self.p2
x1,y1 = canvas.toScreen(p1.x,p1.y)
x2,y2 = canvas.toScreen(p2.x,p2.y)
return canvas.create_rectangle(x1,y1,x2,y2,options)

def clone(self):
other = Rectangle(self.p1, self.p2)
other.config = self.config.copy()
return other

class Oval(_BBox):

def __init__(self, p1, p2):
_BBox.__init__(self, p1, p2)

def clone(self):
other = Oval(self.p1, self.p2)
other.config = self.config.copy()
return other

def _draw(self, canvas, options):
p1 = self.p1
p2 = self.p2
x1,y1 = canvas.toScreen(p1.x,p1.y)
x2,y2 = canvas.toScreen(p2.x,p2.y)
return canvas.create_oval(x1,y1,x2,y2,options)

class Circle(Oval):

Oval.__init__(self, p1, p2)

def clone(self):
other.config = self.config.copy()
return other

class Line(_BBox):

def __init__(self, p1, p2):
_BBox.__init__(self, p1, p2, ["arrow","fill","width"])
self.setFill(DEFAULT_CONFIG['outline'])
self.setOutline = self.setFill

def clone(self):
other = Line(self.p1, self.p2)
other.config = self.config.copy()
return other

def _draw(self, canvas, options):
p1 = self.p1
p2 = self.p2
x1,y1 = canvas.toScreen(p1.x,p1.y)
x2,y2 = canvas.toScreen(p2.x,p2.y)
return canvas.create_line(x1,y1,x2,y2,options)

def setArrow(self, option):
if not option in ["first","last","both","none"]:
self._reconfig("arrow", option)

class Polygon(GraphicsObject):

def __init__(self, *points):
# if points passed as a list, extract it
if len(points) == 1 and type(points[0] == type([])):
points = points[0]
self.points = map(Point.clone, points)
GraphicsObject.__init__(self, ["outline", "width", "fill"])

def clone(self):
other = apply(Polygon, self.points)
other.config = self.config.copy()
return other

def getPoints(self):
return map(Point.clone, self.points)

def _move(self, dx, dy):
for p in self.points:
p.move(dx,dy)

def _draw(self, canvas, options):
args = [canvas]
for p in self.points:
x,y = canvas.toScreen(p.x,p.y)
args.append(x)
args.append(y)
args.append(options)
return apply(GraphWin.create_polygon, args)

class Text(GraphicsObject):

def __init__(self, p, text):
GraphicsObject.__init__(self, ["justify","fill","text","font"])
self.setText(text)
self.anchor = p.clone()
self.setFill(DEFAULT_CONFIG['outline'])
self.setOutline = self.setFill

def _draw(self, canvas, options):
p = self.anchor
x,y = canvas.toScreen(p.x,p.y)
return canvas.create_text(x,y,options)

def _move(self, dx, dy):
self.anchor.move(dx,dy)

def clone(self):
other = Text(self.anchor, self.config['text'])
other.config = self.config.copy()
return other

def setText(self,text):
self._reconfig("text", text)

def getText(self):
return self.config["text"]

def getAnchor(self):
return self.anchor.clone()

def setFace(self, face):
if face in ['helvetica','arial','courier','times roman']:
f,s,b = self.config['font']
self._reconfig("font",(face,s,b))
else:

def setSize(self, size):
if 5 <= size <= 36:
f,s,b = self.config['font']
self._reconfig("font", (f,size,b))
else:

def setStyle(self, style):
if style in ['bold','normal','italic', 'bold italic']:
f,s,b = self.config['font']
self._reconfig("font", (f,s,style))
else:

def setTextColor(self, color):
self.setFill(color)

class Entry(GraphicsObject):

def __init__(self, p, width):
GraphicsObject.__init__(self, [])
self.anchor = p.clone()
#print self.anchor
self.width = width
#self.text = tk.StringVar(_root)
#self.text.set("")
self.text = _tkCall(tk.StringVar, _root)
_tkCall(self.text.set, "")
self.fill = "gray"
self.color = "black"
self.font = DEFAULT_CONFIG['font']
self.entry = None

def _draw(self, canvas, options):
p = self.anchor
x,y = canvas.toScreen(p.x,p.y)
frm = tk.Frame(canvas.master)
self.entry = tk.Entry(frm,
width=self.width,
textvariable=self.text,
bg = self.fill,
fg = self.color,
font=self.font)
self.entry.pack()
#self.setFill(self.fill)
return canvas.create_window(x,y,window=frm)

def getText(self):
return _tkCall(self.text.get)

def _move(self, dx, dy):
self.anchor.move(dx,dy)

def getAnchor(self):
return self.anchor.clone()

def clone(self):
other = Entry(self.anchor, self.width)
return _tkCall(self.__clone_help, other)

def __clone_help(self, other):
other.config = self.config.copy()
other.text = tk.StringVar()
other.text.set(self.text.get())
other.fill = self.fill
return other

def setText(self, t):
#self.text.set(t)
_tkCall(self.text.set, t)

def setFill(self, color):
self.fill = color
if self.entry:
#self.entry.config(bg=color)
_tkExec(self.entry.config,bg=color)

def _setFontComponent(self, which, value):
font = list(self.font)
font[which] = value
self.font = tuple(font)
if self.entry:
#self.entry.config(font=self.font)
_tkExec(self.entry.config, font=self.font)

def setFace(self, face):
if face in ['helvetica','arial','courier','times roman']:
self._setFontComponent(0, face)
else:

def setSize(self, size):
if 5 <= size <= 36:
self._setFontComponent(1,size)
else:

def setStyle(self, style):
if style in ['bold','normal','italic', 'bold italic']:
self._setFontComponent(2,style)
else:

def setTextColor(self, color):
self.color=color
if self.entry:
#self.entry.config(fg=color)
_tkExec(self.entry.config,fg=color)

class Image(GraphicsObject):

idCount = 0
imageCache = {} # tk photoimages go here to avoid GC while drawn

def __init__(self, p, pixmap):
GraphicsObject.__init__(self, [])
self.anchor = p.clone()
self.imageId = Image.idCount
Image.idCount = Image.idCount + 1
if type(pixmap) == type(""):
self.img = tk.PhotoImage(file=pixmap, master=_root)
else:
self.img = pixmap.image

def _draw(self, canvas, options):
p = self.anchor
x,y = canvas.toScreen(p.x,p.y)
self.imageCache[self.imageId] = self.img # save a reference
return canvas.create_image(x,y,image=self.img)

def _move(self, dx, dy):
self.anchor.move(dx,dy)

def undraw(self):
del self.imageCache[self.imageId]  # allow gc of tk photoimage
GraphicsObject.undraw(self)

def getAnchor(self):
return self.anchor.clone()

def clone(self):
imgCopy = Pixmap(_tkCall(self.img.copy))
other = Image(self.anchor, imgCopy)
other.config = self.config.copy()
return other

class Pixmap:
"""Pixmap represents an image as a 2D array of color values.
A Pixmap can be made from a file (gif or ppm):

pic = Pixmap("myPicture.gif")

or initialized to a given size (initially transparent):

pic = Pixmap(512, 512)

"""

def __init__(self, *args):
if len(args) == 1: # a file name or pixmap
if type(args[0]) == type(""):
self.image = _tkCall(tk.PhotoImage, file=args[0], master=_root)
else:
self.image = args[0]
else: # arguments are width and height
width, height = args
self.image = _tkCall(tk.PhotoImage, master=_root,
width=width, height=height)

def getWidth(self):
"""Returns the width of the image in pixels"""
return _tkCall(self.image.width)

def getHeight(self):
"""Returns the height of the image in pixels"""
return _tkCall(self.image.height)

def getPixel(self, x, y):
"""Returns a list [r,g,b] with the RGB color values for pixel (x,y)
r,g,b are in range(256)

"""

value = _tkCall(self.image.get, x,y)
if type(value) ==  int:
return [value, value, value]
else:
return map(int, value.split())

def setPixel(self, x, y, (r,g,b)):
"""Sets pixel (x,y) to the color given by RGB values r, g, and b.
r,g,b should be in range(256)

"""

_tkExec(self.image.put, "{%s}"%color_rgb(r,g,b), (x, y))

def clone(self):
"""Returns a copy of this Pixmap"""
return Pixmap(self.image.copy())

def save(self, filename):
"""Saves the pixmap image to filename.
The format for the save image is determined from the filname extension.

"""

path, name = os.path.split(filename)
ext = name.split(".")[-1]
_tkExec(self.image.write, filename, format=ext)

def color_rgb(r,g,b):
"""r,g,b are intensities of red, green, and blue in range(256)
Returns color specifier string for the resulting color"""
return "#%02x%02x%02x" % (r,g,b)

def test():
win = GraphWin()
win.setCoords(0,0,10,10)
t = Text(Point(5,5), "Centered Text")
t.draw(win)
p = Polygon(Point(1,1), Point(5,3), Point(2,7))
p.draw(win)
e = Entry(Point(5,6), 10)
e.draw(win)
win.getMouse()
p.setFill("red")
p.setOutline("blue")
p.setWidth(2)
s = ""
for pt in p.getPoints():
s = s + "(%0.1f,%0.1f) " % (pt.getX(), pt.getY())
t.setText(e.getText())
e.setFill("green")
e.setText("Spam!")
e.move(2,0)
win.getMouse()
p.move(2,3)
s = ""
for pt in p.getPoints():
s = s + "(%0.1f,%0.1f) " % (pt.getX(), pt.getY())
t.setText(s)
win.getMouse()
p.undraw()
e.undraw()
t.setStyle("bold")
win.getMouse()
t.setStyle("normal")
win.getMouse()
t.setStyle("italic")
win.getMouse()
t.setStyle("bold italic")
win.getMouse()
t.setSize(14)
win.getMouse()
t.setFace("arial")
t.setSize(20)
win.getMouse()
win.close()

if __name__ == "__main__":
test()

Editor's note:

John Zelle, Ph.D. teaches Python at Wartburg College
he is the author of graphics.py used by a number of schools instead
of Tkinter

Here is the graphics module (a thin wrapper for Tkinter) ...
http://mcsp.wartburg.edu/zelle/python/graphics.py
also has a nice documentation ...
http://mcsp.wartburg.edu/zelle/pytho...s/graphics.pdf

I have to warn you, this code contains the absolute nono of Python coding, namely mixed tab and space indentations in certain parts of it.

using an example from a programing book i have come up with this. but its no where near working ...

def histogram():
# initialize variables
longestLength = 1
list = []

start = input("Please enter the begining integer for the range: ")
for n in range (start, start + 10):
length = chain(n)
list.append(length)
if longestLength <= chain(n):
longestLength = n
length = chain(n)
print length
print list

win = GraphWin("Draw Circles", 500,500)
win.setBackground('orange')
win.setCoords(-1.75, -200, 11.5, 10400)
Text(Point(-1,0), ' 5').draw(win)
Text(Point(-1,2500), ' 10').draw(win)
Text(Point(-1,5000), ' 15').draw(win)
Text(Point(-1,7500), ' 20').draw(win)

for j in list:

bar = Rectangle(Point(j, 0), Point(j+1, list[j]))
bar.setFill('yellow')
bar.setOutline('black')
bar.draw(win)

raw_input("Press <Enter> to quit.")
win.close()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.