sneekula 969 Nearly a Posting Maven

Just a quick example on how to use the wx.grid.PyGridTableBase with wxPython's wx.grid.Grid. Provides a simple way to create, load and use a spreadsheet like grid:

# exploring wxPython's wx.grid.Grid()
# load grid via a '(row, col): value' dictionary and a table class
# that inherits and applies wx.grid.PyGridTableBase
# snee

import wx
import wx.grid

class MyFrame(wx.Frame):
    def __init__(self, header_list, data_dict):
        wx.Frame.__init__(self, None, wx.ID_ANY,
            title="ACME Inc. Staff Stats", size=(510,200))

        self.grid = wx.grid.Grid(self)
        self.grid.SetRowLabelSize(30)     # sets leading row width
        self.grid.SetDefaultRowSize(20)   # sets all row height
        self.grid.SetColLabelSize(30)     # sets leading col height
        self.grid.SetDefaultColSize(80)  # sets all col width

        # select the cell with a mouse left click
        self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.cell_click)

        # the table takes care of all the grid stuff
        table = MyTable(header_list, data_dict)
        self.grid.SetTable(table, True)
        
        # optional, calculate rows of data needed for fun stats
        self.rows = max(data_dict.keys())[0] + 1

    def cell_click(self, event):
        """cell has been left clicked"""
        row = event.GetRow()
        col = event.GetCol()
        # move the grid's cursor to frame the cell
        self.grid.SetGridCursor(row, col)
        # you can do some fun stats with the numbers
        num = []
        if col > 0:
            #num = []
            for nrow in range(self.rows):
                num.append(float(self.grid.GetCellValue(nrow, col)))
        val = self.grid.GetCellValue(row, col)
        if num:
            sf = "r%dc%d %s  max=%.1f min=%.1f avg=%.1f" % \
               (row, col, val, max(num), min(num), sum(num)/nrow)
        else:
            sf = "r%dc%d %s" % (row, col, val)
        self.SetTitle(sf)


class MyTable(wx.grid.PyGridTableBase):
    def __init__(self, header_list, data_dict):
        wx.grid.PyGridTableBase.__init__(self)
        self.data = data_dict
        # calculate rows and cols needed to fit the data
        self.rows = max(data_dict.keys())[0] + 1
        self.cols = max(data_dict.keys())[1] + …
sneekula 969 Nearly a Posting Maven

Yes Gloria, Tkinter has a combo box, but it's called an option menu. Here is an example:

# using Tkinter's Optionmenu() as a combobox

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def select():
    sf = "value is %s" % var.get()
    root.title(sf)
    # optional
    color = var.get()
    root['bg'] = color


root = tk.Tk()
# use width x height + x_offset + y_offset (no spaces!)
root.geometry("%dx%d+%d+%d" % (330, 80, 200, 150))
root.title("tk.Optionmenu as combobox")

var = tk.StringVar(root)
# initial value
var.set('red')

choices = ['red', 'green', 'blue', 'yellow','white', 'magenta']
option = tk.OptionMenu(root, var, *choices)
option.pack(side='left', padx=10, pady=10)

button = tk.Button(root, text="check value slected", command=select)
button.pack(side='left', padx=20, pady=10)

root.mainloop()
sneekula 969 Nearly a Posting Maven

Never look at the trombones, it only encourages them.
~~~ Richard Wagner

sneekula 969 Nearly a Posting Maven

The module turtle that comes with Python makes for interesting projects. Here is a function that draws a hexagon:

# explore module turtle (uses the Tkinter GUI toolkit)
# usually included in the Python2 and Python3  installation
# a function to draw 6 turtle lines to form a hexagon
# snee

import turtle as tu

tu.title('hexagon function')

def t_hexagon(x, y, side, color):
    """
    draw an equilateral hexagon, each side has length=side
    starting at coordinates x, y (upper side, right corner)
    """
    tu.up()  # pen up
    tu.goto(x, y)
    tu.down()  # pen down
    tu.color(color)
    for k in range(6):
        tu.right(360/6)
        tu.forward(side)

# optional ('normal' is default) ...
# values for speed are 'fastest' (no delay), 'fast', (delay 5ms),
# 'normal' (delay 10ms), 'slow' (delay 15ms), 'slowest' (delay 20ms)
#tu.speed('fastest')

# optional pen width (default is 1)
tu.width(2)

# turtle by default starts at x=0, y=0
# wich is the center of a (ca. 450x550) window
# pick +x units to the right, +y units up,
# -x units to the left, -y units down
x = 50
y = 100
side = 100
color = 'red'
t_hexagon(x, y, side, color)

# keep showing until window corner x is clicked
tu.done()

If you run this code, you will see that the hexagon rests on its side. Your challenge will be to rewrite the function so it will draw the hexagon resting on its tip.

sneekula 969 Nearly a Posting Maven

You have to read up on the slicing operator in the Python Manual.

Generally you can slice a sequence with [start: end: step]
By default start=0, end=len(seq), step=1
step=-1 goes from the end to the beginning of the sequence, hence your reverse.

For some nice slicing examples see post #4 at;
http://www.daniweb.com/forums/post104865.html#post104865

nunos commented: very clarifying post. link to good examples. +1
sneekula 969 Nearly a Posting Maven

Courier is the most common font to space all character equal.

Lingson commented: Nice and direct solution! +1
sneekula 969 Nearly a Posting Maven
sneekula 969 Nearly a Posting Maven

Just a basic text editor written with the Tkinter GUI toolkit:

# a very simple Tkinter editor
# shows you how to create a menu and
# use the file dialog to read and write files of text data
# snee

try:
    # Python2
    import Tkinter as tk
    import tkFileDialog as tkfd
except ImportError:
    # Python3
    import tkinter as tk
    import tkinter.filedialog as tkfd

class MyEditor(object):
    def __init__(self, master):
        frame = tk.Frame(master)
        frame.pack()
        self.text = tk.Text(bg='white')
        self.text.pack()
        
        menu = tk.Menu(master)
        root.config(menu=menu)
        # file menu
        filemenu = tk.Menu(menu, tearoff=0)
        menu.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="New", command=self.new_text)
        filemenu.add_command(label="Open", command=self.file_open)
        filemenu.add_command(label="SaveAs", command=self.file_saveas)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.do_exit)
        
        # start with cursor in the editor area
        self.text.focus()
        
    def new_text(self):
        """clear the text area so you can start new text"""
        self.text.delete(0.0, 'end')
    
    def file_open(self):
        """open a file to read"""
        # the filetype mask (default is all files)
        mask = \
        [("Text and Python files","*.txt *.py *.pyw"),
        ("HTML files","*.htm *.html"),
        ("All files","*.*")]
        fin = tkfd.askopenfile(filetypes=mask, mode='r')
        text = fin.read()
        if text != None:
            # delete any old text first
            self.text.delete(0.0, 'end')
            self.text.insert('end', text)

    def file_saveas(self):
        """get a filename and save your text to it"""
        # default extension is optional, will add .txt if missing
        fout = tkfd.asksaveasfile(mode='w', defaultextension=".txt")
        text2save = str(self.text.get(0.0, 'end'))
        fout.write(text2save)
        fout.close()

    def do_exit(self):
        root.destroy()

root = tk.Tk()
# use width x height + x_offset + y_offset (no spaces!)
root.geometry("%dx%d+%d+%d" % (500, 300, 120, 80))
root.title("my very simple editor")
myed = MyEditor(root)
root.mainloop()

A nice template you make improvements on.

sneekula 969 Nearly a Posting Maven

The Tkinter drawing canvas can be fun. Here are two short programs that can be used by an artist for creative things:

# draw a circle with center (x, y) and fixed radius at
# each mouse (x, y) click point

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def draw_circle(event):
    '''
    draw a circle with given radius and its center
    at the mouse click position
    '''
    x = event.x
    y = event.y
    radius = 40
    # to draw a circle you need to get the upper left
    # and lower right corner coordinates of a square
    rect = get_square(x, y, radius)
    # draw the cicle that fits into the rect/square
    circle = cv.create_oval(rect)

def get_square(x, y, radius):
    '''
    given the center=(x, y) and radius
    calculate the square for a circle to fit into
    return x1, y1, x2, y2 of the square's ulc=(x1, y1) and
    lrc=(x2, y2) diagonal corner coordinates
    '''
    x1 = x - radius
    y1 = y - radius
    x2 = x + radius
    y2 = y + radius
    return x1, y1, x2, y2

# create the basic window, let's call it 'root'
root = tk.Tk()
# only set x=100, y=80 position of root upper left corner
root.geometry("+%d+%d" % (100, 80))
root.title("click the mouse on the green area")

# create a canvas to draw on
cv = tk.Canvas(root, width=600, height=600, bg='green')
# position the canvas
cv.grid()

# respond to the mouse as it is clicked
root.bind("<Button-1>", draw_circle)

# start the …
sneekula 969 Nearly a Posting Maven

If you have young children at home, or are yourself a young child at heart, there is a delightful Python module called frog, that does turtle like drawings and more:

# frog is a somewhat advanced turtle graphics module
# get frog-1.0.1.zip from:
# http://www.zahlenfreund.de/python/frog.html
# see also:
# http://pypi.python.org/pypi/frog/1.0.0
# unzip and copy frog.py into the Python lib folder
# or use it in the working folder
# works with Python2 and Python3

import frog

# pond forms the canvas
pond = frog.Pool()
pond.title = "Watch the frog move and draw"
pond.bgcolor = "lightblue"
# kermit forms the drawing pen
kermit = frog.Frog(pond)
kermit.shape = "frog"
kermit.bodycolor = "green"
# kermit draws a square 
# starts at the center of the pond
for n in range(4):
    kermit.move(100)
    kermit.turn(90)
# turn kermit in the other direction
kermit.turn(180)
for n in range(4):
    kermit.move(100)
    kermit.turn(90)
pond.ready()

Just a little more for the fun of it:

# get frog-1.0.1.zip from:
# http://www.zahlenfreund.de/python/frog.html
# unzip and copy frog.py into the Python lib folder
# or use it in the working folder
# works with Python2 and Python3

import frog

canvas = frog.Pool()
canvas.setbgcolor('green')
# use the default triangle shape
pen = frog.Frog(canvas)
pen.color = "red"
# pen normally starts in the canvas center
# make it jump (no drawing) left and then down
pen.jump(-50)
pen.turn(90)
pen.jump(-25)
pen.turn(270)
# the pen draws a number of 'pentagon shapes' 
# starts at the center and forms a star
for …
sneekula 969 Nearly a Posting Maven

How about a blank icon as a spacer? Or maybe just a label with a few spaces?

Stefano Mtangoo commented: Blank icon? Great Idea! +7
sneekula 969 Nearly a Posting Maven

Here is a short code that allows you to list all the files in a given directory and its subdirectories:

#!/usr/bin/env python2.5

# list all files in a directory tree using recursion
# shows full file paths of all files in subdirectories too
# works with Python2 and Python3

import os

def mylister(currdir, mylist=[]):
    """default mylist becomes static"""
    #print( "looking at %s" % currdir )  # test
    for file in os.listdir(currdir):
        # add directory to filename
        path = os.path.join(currdir, file)
        if not os.path.isdir(path):
            #print(path)  # test
            mylist.append(path)
        else:
            # recurse into subdirectories
            mylister(path)
    return mylist

# this allows the module mylister to be tested
if __name__ == '__main__':
    # pick a folder/directory
    # for Windows use something like this
    #folder = r"C:\Temp"
    # for Linux use something like this
    folder = "/home/dell/Documents"
    path_list = mylister(folder)
    for path in path_list:
        print(path)

"""my partial result -->
/home/dell/Documents/about.html
/home/dell/Documents/_sources/user/basics.rec.txt
/home/dell/Documents/_sources/user/performance.txt
/home/dell/Documents/_sources/user/basics.indexing.txt
/home/dell/Documents/_sources/user/basics.txt
/home/dell/Documents/_sources/user/basics.creation.txt
/home/dell/Documents/_sources/user/misc.txt
/home/dell/Documents/_sources/user/index.txt
...
"""

Change the code in such a manner that, for instance, only image files are listed. Image files would have extensions like .jpg .png .gif .bmp an so on.

sneekula 969 Nearly a Posting Maven

Here is a basic template of a window, 2 buttons and a label using the pygtk toolkit:

# a very basic pygtk window template
# with two buttons and one label
# snee

import pygtk
pygtk.require('2.0')
import gtk

class MyWindow(object):
    def __init__(self):
        # type=gtk.WINDOW_TOPLEVEL is default
        self.window = gtk.Window()
        # pygtk needs this
        # attach destroy signal to terminate application properly
        self.window.connect("destroy", lambda w: gtk.main_quit())
        # title bar caption
        self.window.set_title("gtk.Window template")
        # put upper left corner on display coordinates (x, y)
        self.window.move(100, 80)
        # resize(width, height)
        self.window.resize(350, 150)
        
        # create 2 button widgets and a label widget
        button1 = gtk.Button("Button 1")
        # connect mouse click to a callback
        button1.connect("clicked", self.callback, "Tom")
        button2 = gtk.Button("Button 2")
        # connect mouse click to a callback
        button2.connect("clicked", self.callback, "Frank")
        self.label = gtk.Label("Hello!")

        # create a vertical box to pack the widgets into
        box_v = gtk.VBox(False, 0)
        self.window.add(box_v)
        # now pack the widgets into the box (top to bottom order)
        box_v.pack_start(button1, False, False, 0)
        box_v.pack_start(button2, False, False, 0)
        box_v.pack_start(self.label, True, True, 0)

        # now show all the widgets including the window
        button1.show()
        button2.show()
        self.label.show()
        box_v.show()
        self.window.show()

    def callback(self, widget, data=None):
        s = "You clicked %s's button" % data
        self.window.set_title(s)
        if data == "Tom":
            self.label.set_text("Major Tom")
        else:
            self.label.set_text("Major Frank Burns")
        

MyWindow()
gtk.main()
sneekula 969 Nearly a Posting Maven

Here is an example of a scrolled Tkinter canvas to display a series of drawn objects or pictures:

# example of a Tkinter scrolled canvas class
# snee

try:
    # for Python2
    import Tkinter as tk
except ImportError:
    # for Python3
    import tkinter as tk

class ScrolledCanvas(tk.Frame):
    def __init__(self, parent=None, color='brown'):
        tk.Frame.__init__(self, parent)
        self.pack(expand='yes', fill='both')
        self.parent = parent
        
        canvas = tk.Canvas(self, bg=color, relief='sunken')
        #canvas.config(width=300, height=200)
        canvas.config(scrollregion=(0, 0, 300, 1000))
        canvas.config(highlightthickness=0)

        sbar = tk.Scrollbar(self)
        # vertical scrollbar
        sbar.config(command=canvas.yview)
        canvas.config(yscrollcommand=sbar.set)
        sbar.pack(side='right', fill='y')
        canvas.pack(side='left', expand='yes', fill='both')

        # put in some text for testing ...
        for k in range(10):
            s = 'now calling #' + str(k)
            canvas.create_text(150, 50+(k*100), text=s, fill='beige')
        # for testing canvas (x, y)
        canvas.bind('<Double-1>', self.onDoubleClick)
        self.canvas = canvas
        
    def onDoubleClick(self, event):
        """show location (x, y) of double click on canvas"""
        #print( event.x, event.y )
        x = self.canvas.canvasx(event.x)
        y = self.canvas.canvasy(event.y)
        s = "x = %s  y = %s" % (x, y)
        self.parent.title(s)

if __name__ == '__main__':
    root = tk.Tk()
    # use width x height + x_offset + y_offset (no spaces!)
    root.geometry("%dx%d+%d+%d" % (350, 250, 100, 80))
    root.title('testing the scrolled canvas')
    ScrolledCanvas(root).mainloop()
sneekula 969 Nearly a Posting Maven

Set up a formatted string before you send it to the Textbox. Here is an example:

# example to set up a table formatted string

import math

# set up the format strings (use - for left justified)
header  = "%-12s %-12s %-12s \n"
line_fs = "%-12f %-12.4f %-12.4f \n"

table = ''
table += (header % ('radians', 'sine', 'cosine'))
for x in range(0, 11):
    rad = math.radians(x)
    table += (line_fs % (rad, math.sin(rad), math.cos(rad)))

print(table)

"""my output (use a fixed font like Courier) -->
radians      sine         cosine
0.000000     0.0000       1.0000
0.017453     0.0175       0.9998
0.034907     0.0349       0.9994
0.052360     0.0523       0.9986
0.069813     0.0698       0.9976
0.087266     0.0872       0.9962
0.104720     0.1045       0.9945
0.122173     0.1219       0.9925
0.139626     0.1392       0.9903
0.157080     0.1564       0.9877
0.174533     0.1736       0.9848
"""
catcit commented: Thanks! +1
vegaseat commented: very nice +13
sneekula 969 Nearly a Posting Maven

In Python most everything is an objects, so you are using OOP from the start.
If you talking about the use of classes, then basically you have another tool to organize larger programs.

You can collect functions that belong together under the class header. These function are commonly called methods of a class. This way you can create several different instances of the class, each containing the same methods. That is where the power comes in, since you don't have to rewrite the class every time. Python keeps track of which instance you are using. Here is an example:

# a look at a simple Python class

class Animal(object):
    # uses newer class style, inheriting very basic class 'object'
    def __init__(self, animal, sound):
        # __init__() is the 'constructor' of the class instance
        # when you create an instance of Animal you have to supply
        # it with the name and the sound of the animal
        # 'self' refers to the instance
        # if the instance is dog, then
        # name and sound will be that of the dog
        # 'self' also makes name and sound available
        # to all the methods within the class
        self.name = animal
        self.sound = sound
        
    def speak(self):
        # a method's arguments always start with self
        print( "The %s goes %s" % (self.name, self.sound) )


# create a few class instances
# remember to supply the name and the sound for each animal
dog = Animal("dog", "woof")
cat = Animal("cat", "meeouw")
cow = …
vegaseat commented: very nice example +13
sneekula 969 Nearly a Posting Maven

For those of you who want experience vegaseat's sweet Tinter tkk example at:
http://www.daniweb.com/forums/post921416-25.html
on your Linux machines, in my case Ubuntu (Python 3.1 is not in the repository yet), here is an easy installation of Python 3.1:

Download ActivePython-3.1.0.1-linux-x86.tar.gz via
http://downloads.activestate.com/ActivePython/linux/3.1/ActivePython-3.1.0.1-linux-x86.tar.gz
from:
http://www.activestate.com/activepython/python3/

Extract to the Desktop

In the terminal change to the proper directory:

cd ~/Desktop/ActivePython-3.1.0.1-linux-x86/

Then run:

sudo ./install.sh

As install directory I entered something easy like:

/home/dell/python/3.1

The installation takes a short time. Now create a symbolic link:

sudo ln -s /home/dell/python/3.1/bin/python3.1 /usr/local/bin/python3.1

Now you are ready to enjoy Python 3.1

# to run a scripts with Python3.1
# with the Geany IDE you can set 'Build'/'Set Includes and Arguments'
# 'Execute' to python3.1 "%f"

sneekula 969 Nearly a Posting Maven

Write a program that goes through a folder of source/text files and lists all the file names that contain a given search word (or combination of search words).

sneekula 969 Nearly a Posting Maven

Some options with a basic Tkinter window:

# set position and size of a Tkinter window

try:
    # for Python2
    import Tkinter as tk
except ImportError:
    # for Python3
    import tkinter as tk

#root = tk.Tk()
root = tk.Tk(className="My Title")  # sets title too
# or give it your title this way
#root.title("My Title")

w = 300
h = 200
x = 50
y = 100
# use width x height + x_offset + y_offset (no spaces!)
root.geometry("%dx%d+%d+%d" % (w, h, x, y))

# make Tk window not resizable, also disables the maximize button
#root.resizable(width=FALSE, height=FALSE)
# or ...
#root.resizable(0, 0)

# or make root window full screen
#root.state('zoomed')

# give it a colorful frame
frame = tk.Frame(root, bg='green')
frame.pack(fill='both', expand='yes')

root.mainloop()
sneekula 969 Nearly a Posting Maven

Since Pygame does not have a file dialog, we can use Tkinter's file dialog and withdrawing the root so it doesn't clash with Pygame's eventloop:

# experiments with module pygame
# free from: http://www.pygame.org/
# load and display an image using pygame and Tkinter's file dialog

import pygame as pg

# initialize pygame
pg.init()

#---------- uses Tkinter to open an image filename ------------------
import Tkinter as tk
import tkFileDialog as tkfd
root = tk.Tk()
root.withdraw()
dirname = tkfd.askdirectory()
mask = [("GIF and JPEG files","*.gif *.jpg")]
image_file = tkfd.askopenfilename(initialdir=dirname, filetypes=mask)
#--------------------------------------------------------------------

# RGB color tuple used by pygame
white = (255, 255, 255)

# create a 300x300 white screen
screen = pg.display.set_mode((300,300))
screen.fill(white)

# load the image from a file
image = pg.image.load(image_file)

# draw image, position the image ulc at x=50, y=20
screen.blit(image, (50, 20))

# nothing gets displayed until one updates the screen
pg.display.flip()

# start event loop and wait until
# the user clicks on the window corner x
while True:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            raise SystemExit
sneekula 969 Nearly a Posting Maven

If people do not believe that mathematics is simple, it is only because they do not realize how complicated life is.
~~~ John von Neumann

sneekula 969 Nearly a Posting Maven

Probably one of those many pop up ads, or the ghost of Dani Web.

ahihihi... commented: :twisted: +1
sneekula 969 Nearly a Posting Maven

Here is the start of a Phone or Address Book:

# create a dictionary of class instance values
# can be expanded to an address book
# note: email is a Python module, so use e_mail
# snee

class DataBook(object):
    def __init__(self, home, mobile, e_mail):
        self.home = home
        self.mobile = mobile
        self.e_mail = e_mail
        self.get_info()

    def get_info(self):
        sf = \
"""Home Phone = %s
Mobile Phone = %s
Email = %s
"""
        return sf % (self.home, self.mobile, self.e_mail)


name_dic = {}

# first set of data
name = 'frank millato'
home = '123-456-7890'
mobile = '456-789-0123'
e_mail = 'frank23@gmail.com'

# the name string is the key and has to be unique
name_dic[name] = DataBook(home, mobile, e_mail)

# second set of data
name = 'bob dork'
home = '234-567-8901'
mobile = '567-690-1234'
e_mail = 'bob.dork@hotmail.com'

name_dic[name] = DataBook(home, mobile, e_mail)

# get bob's email
name = 'bob dork'
print( name_dic[name].e_mail )

print('-'*40)

# get the info for all names added so far
for key in name_dic:
    print( "Name = %s" % key )
    print( name_dic[key].get_info() )

print('-'*40)

# search for part of a name and find the mobile
search = 'dork'
for key in name_dic:
    if search in key:
        print( "%s has mobile = %s" % (key, name_dic[key].mobile) )


# to save the data, you can simply save it as a text file
# where each line is name, home, mobile, e_mail
filename = "Names1.txt"
fout = open(filename, "w")
for key in name_dic:
    k = name_dic[key]
    s = "%s,%s,%s,%s\n" % …
sneekula 969 Nearly a Posting Maven

In the English language you can add a suffix to a number, so for instance first becomes 1st, second 2nd, third 3rd, fourth 4th and so on. Here is a little Python program that does it for you, and teaches a few list tricks too:

# add the proper suffix to integer numbers
# the suffix list index coincides with the number
# apply modulus 100 for numbers that exceed the list index
# snee

# list_0to9 also holds true for list_20to29 etc.
list_0to9 = ['th', 'st', 'nd', 'rd'] + ['th']*6
# 11th to 13th are exceptions
list_10to19 = ['th']*10

# suffix list for numbers 0 to 99
suffix_list = list_0to9 + list_10to19 + (list_0to9)*8

#print suffix_list

# test it
for x in range(1000):
    # use modulus 100 to recycle through the list
    # in case numbers exceed the list index
    print( "%d%s" % (x, suffix_list[x%100]) )

"""
part of my output -->
0th
1st
2nd
3rd
4th
5th
6th
7th
8th
9th
10th
11th
12th
13th
14th
15th
16th
17th
18th
19th
20th
21st
22nd
23rd
24th
25th
...
...
990th
991st
992nd
993rd
994th
995th
996th
997th
998th
999th
"""
Ene Uran commented: nice code indeed! +7
sneekula 969 Nearly a Posting Maven

I get mail, therefore I am.
~~~ Scott Adams

sneekula 969 Nearly a Posting Maven

Floating point numbers are often close approximations of a value, very close, but approximations never the less. So if you directly compare floating point number results you can get surprises as shown here:

def fuzzyequals(a, b, delta=0.0000001):
    """
    returns true if a is between b-delta and b+delta
    used for comparison of floating point numbers a and b
    """
    return abs(a-b) < delta

a = 0.61
c = 0.49
b = 1.1 - c  # b should be 0.61

# fuzzy comparison
if fuzzyequals(a, b):
    print("fuzzy_true")
else:
    print("fuzzy_false")

# direct comparison
if a == b:
    print("direct_true")
else:
    print("direct_false")

# shows true floating point number representation
print("should be [0.61, 0.61, 0.49]")
print([a, b, c])

"""
my output -->
fuzzy_true
direct_false
should be [0.61, 0.61, 0.49]
[0.60999999999999999, 0.6100000000000001, 0.48999999999999999]
"""
sneekula 969 Nearly a Posting Maven

An example how to use an image as a background. In order to make added text transparent, use the Tkinter canvas:

# use a Tkinter canvas for a background image
# add transparent text and other widgets
# with Python3 use   import tkinter as tk
# snee

import Tkinter as tk
 
root = tk.Tk()
root.title('background image')

# pick a .gif image file you have in the working directory
bg_image = tk.PhotoImage(file="Flowers.gif")
w = bg_image.width()
h = bg_image.height()
 
# size the window so the image will fill it
root.geometry("%dx%d+0+0" % (w, h))

cv = tk.Canvas(width=w, height=h)
cv.pack(side='top', fill='both', expand='yes')
cv.create_image(0, 0, image=bg_image, anchor='nw')
 
# add canvas text at coordinates x=15, y=30
# anchor='nw' implies upper left corner coordinates
cv.create_text(15, 30, text="Python Greetings", fill="red", anchor='nw')

# now some button widgets
btn1 = tk.Button(cv, text="Click")
btn1.pack(side='left', padx=10, pady=5, anchor='sw')

btn2 = tk.Button(cv, text="Quit")
btn2.pack(side='left', padx=10, pady=5, anchor='sw')

root.mainloop()
sneekula 969 Nearly a Posting Maven

I like nutella, a chocolaty hazelnut spread, sort of like a much improved peanut butter.

scru commented: yum. +6
sneekula 969 Nearly a Posting Maven

The third-rate mind is only happy when it is thinking with the majority.
The second-rate mind is only happy when it is thinking with the minority.
The first-rate mind is only happy when it is thinking.
~~~ A. A. Milne

sneekula 969 Nearly a Posting Maven

All animals are equal, but some are tastier.

vmanes commented: Orwell is turning in his grave, or laughing his a## off! +9
sneekula 969 Nearly a Posting Maven

Experience is a hard teacher, because the test is given first, the lesson afterwards.
~~~ Vernon Lawson

sneekula 969 Nearly a Posting Maven

Just in case you don't fine wxGlade or BoaConstructor to be quite what you need (or if you just can't get past how ugly they are), you can try QtDesigner for pyQT (comes with the pyQT package).

Beauty and henceforth ugly is in the eye of the beholder!

Actually, the QT_Designer is pretty good and gives XML code that can be converted to a seemingly complex looking Python code.

scru commented: not seemingly, it is complex. But people who use gui builders generally don't care about this sort of stuff. +6
sneekula 969 Nearly a Posting Maven

I did some detective work to find the stock trading value for a given ticker symbol. See if you can use the fruits of my labor and turn this into a more general portfolio tracker:

# find the stock trading value for a given ticker symbol
# tested with Python25

import urllib2

def extract(text, sub1, sub2):
    """
    extract a substring from text between first
    occurances of substrings sub1 and sub2
    """
    return text.split(sub1, 1)[-1].split(sub2, 1)[0]


ticker = 'GE'
url = 'http://finance.yahoo.com/q?s='+ticker
fh = urllib2.urlopen(url)
ticker_html = fh.read()

#print(ticker_html)

for line in ticker_html.split('><'):
    if 'id="yfs_' in line:
        print(line)

print('-'*70)

# narrow it down
for line in ticker_html.split('><'):
    if 'id="yfs_l' in line:
        print(line)

print('-'*70)

# narrow it down even more
for line in ticker_html.split('><'):
    if 'id="yfs_l10_' in line:
        print(line)
        print(extract(line, '>', '<'))
        break
sneekula 969 Nearly a Posting Maven

Statistics are like bikinis. What they reveal is suggestive, but what they conceal is vital.
-- Frank Barkow

sneekula 969 Nearly a Posting Maven

Some cause happiness wherever they go; others, whenever they go.
-- Oscar Wilde

sneekula 969 Nearly a Posting Maven

Also look into (wxPython is used by Boa and wxGlade):
Starting wxPython (GUI code)
http://www.daniweb.com/forums/thread128350.html

and:
Python GUI Programming
http://www.daniweb.com/forums/thread191210.html

Some words of advice, GUI programming will be a steep learning curve. You have to rethink your approach to use the best GUI widget/component to do what you want. For instance, most GUI toolkits will give a large number of input (text entry, sliders, check boxes, radio buttons, list boxes ...) and output (labels, sound, image, canvas, plotters, spreadsheet ...) devices. A GUI Builder will only position the selected widget on a window/frame, you still have to write the code to make it do something.

I look at this way, console programs are for learning Python, GUI programs are for showing what you have learned. Learn Python coding real well, then apply it to a GUI!

sneekula 969 Nearly a Posting Maven

The { and } keys.

sneekula 969 Nearly a Posting Maven

This demonstrates a little function to extract the numeric value from a string like "$12.34/pound" where you want just 12.34 to do calculations:

# extract the numeric value from a data string
# snee

def extract_number(data_str):
    """
    extract the numeric value from a string
    the string should contain only one number
    return the number as int, float or None
    """
    s = ""
    for c in data_str:
        if c in '1234567890.-':
            s += c
    if s:
        # convert number to int or float
        return eval(s)
    else:
        return None


data_raw = """
header
23 bushels
 43 years old
4323 Maiden Lane
-$23.44/kg
 +$12.32
footer
"""

# create a list of the string data
data_list = data_raw.split('\n')
print(data_list)  # test

print('-'*60)

# extract numeric values from the data in the list
for data_str in data_list:
    print(extract_number(data_str))

"""
my result -->
['', 'header', '23 bushels', ' 43 years old', '4323 Maiden Lane',
'-$23.44/kg', ' +$12.32', 'footer', '']
------------------------------------------------------------
None
None
23
43
4323
-23.44
12.32
None
None
"""
sneekula 969 Nearly a Posting Maven

The Bible is full of rules to live by, not secret code!

If someone claims to have discovered secret code, then it is only to pull ignorant folks nose for financial gain or influence peddling.

Salem commented: I thought that's what religion was all about - separating the gullible from their money :) +32
sneekula 969 Nearly a Posting Maven

A man is smoking a cigarette and blowing smoke rings into the air. His girlfriend becomes irritated with the smoke and says, “Can’t you see the warning on the cigarette pack? Smoking is hazardous to your health!”

To which the man replies, “I am a programmer. We don’t worry about warnings; we only worry about errors.”

kvprajapati commented: Great! +3
sneekula 969 Nearly a Posting Maven

The easiest way is to use a wx.RadioBox:

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent=None):
        wx.Frame.__init__(self, parent, wx.ID_ANY, size=(300, 160))
        # match to the number of radiobuttons
        self.mychoices = ['image1', 'image2', 'image3', 'image4']

        # create a box with 4 radio buttons, no labels here
        label_choices = [' ', ' ', ' ', ' ']
        self.radiobox = wx.RadioBox(self, wx.ID_ANY,
            " click on a button ",
            choices=label_choices, style=wx.VERTICAL)
        # bind mouse click to an action
        self.radiobox.Bind(wx.EVT_RADIOBOX, self.onAction)

        # show present selection
        self.onAction(None)

    def onAction(self, event):
        """show the selected choice"""
        index = self.radiobox.GetSelection()
        s = "Selected " + self.mychoices[index]
        # show the result in the frame title
        self.SetTitle(s)


app = wx.App(0)
MyFrame().Show()
app.MainLoop()
sneekula 969 Nearly a Posting Maven

The nice thing about using a GUI toolkit is that you have a large number of widgets available to supply the data input. Here is a Tkinter Temperature Converter example using radio buttons to select the type of conversion and a scale (slider) to set the temperature. Notice that the result is updated as changes to the inputs are made:

#!/usr/bin/env python

# use Tkinter's scale/slider and radiobutton widgets
# for input data to convert temperature values

import Tkinter as tk

def on_click():
    """radio button clicked, change results too"""
    on_move()

def on_move(value=0):
    """use slider position to calculate and display result"""
    # radio button1 is set convert C to F
    if rb_v.get() == id_rb1:
        c = scale.get()
        f = c*9/5.0 + 32
        result = "%s celsius --> %s Fahrenheit" % (c, f)
    # radio button2 is set convert F to C
    else:
        f = scale.get()
        c = (f - 32)*5/9.0
        result = "%s Fahrenheit --> %s Celsius" % (f, c)
    label['text'] = result

root = tk.Tk()
root.title('Temperature Converter')
# use width x height + x_offset + y_offset (no spaces!)
root.geometry("620x110+30+50")

# used by the radio button_id
rb_v  = tk.IntVar()

# the radio buttons allow selection of Celsius or Fahrenheit
id_rb1 = 101
rb1 = tk.Radiobutton(root, text='Celsius to Fahrenheit',
    value=id_rb1, variable=rb_v, command=on_click)
id_rb2 = 102
rb2 = tk.Radiobutton(root, text='Fahrenheit to Celsius',
    value=id_rb2, variable=rb_v, command=on_click)
# start with rb1 selected
rb_v.set(id_rb1)

# the scale (or slider) selects the temperature
# from -50 to +300
# (from_ is used because from is a …
sneekula 969 Nearly a Posting Maven

The easiest way is to create a dictionary where the key is the (x,y) location tuple and the value is the (r,g,b) color tuple of the pixel:

#!/usr/bin/env python

# image data analysis using PIL, keep track of pixel value
# (r,g,b) and location (x,y) with a (x,y):(r,g,b) dictionary

from PIL import Image

# the french_flag test file is a 24X16 bitmap and
# has a simple blue-white-red, left to right pattern
img = Image.open("french_flag.bmp")
width, height = img.size

#print width, height

pixel_list = list(img.getdata())

# create a (x,y):(r,g,b) dictionary
# where (x,y) are the location coordinates an image point
# and (r,g,b) is the value of the pixel at that point
pixel_dict = {}
ix = 0
# rows
for y in range(height):
    # columns
    for x in range(width):
        pixel_dict[(x, y)] = pixel_list[ix]
        #print x, y, ix
        ix += 1

# testing ...
# show contents of the first row
y = 0
for x in range(width):
    print( "(%d, %d): %s"% (x, y, pixel_dict[(x, y)]) )

'''
print('-'*20)

# show contents of the dictionary sorted by (x, y) coordinates
for k, v in sorted(pixel_dict.items()):
    print k, v
'''

print('-'*20)

# get the pixel (r, g, b) value at point (x, y)
x = 1
y = 10
print(pixel_dict[(x, y)])
scru commented: that's easy but very wasteful. you end up with three copies of the exact same data in memory, and for images that can be a lot. +6
sneekula 969 Nearly a Posting Maven

Tkinter has the reputation to look kind of homely on Windows computers. Actually, on my Ubuntu/Linux computer it doesn't look bad at all. Here is a typical listbox example using the Tkinter GUI toolkit that comes with just about every Python installation. Yes, if you use the new Python3, it comes with Tkinter too. Just remember that Tkinter is now a package and you have to import tkinter rather than Tkinter:

#!/usr/bin/env python

# create a scrollable listbox using Tkinter
# load the listbox with tasty cheese data
# and select your favorite cheese with the mouse
# with Python3 use   import tkinter as tk

import Tkinter as tk

def get_list(event):
    """
    function to read the listbox selection
    and put the result in a label widget
    """
    # get selected line index
    index = listbox.curselection()[0]
    # get the line's text
    seltext = listbox.get(index)
    # put the selected text in the label
    label['text'] = seltext

root = tk.Tk()
root.title("Cheeses")
# use width x height + x_offset + y_offset (no spaces!)
root.geometry("180x300+30+50")

# create a label (width in characters)
s = "Click on a cheese"
label = tk.Label(root, text= s, width=15)
label.grid(row=0, column=0)

# create a listbox (height in characters/lines)
# give it a nice yellow background (bg) color
listbox = tk.Listbox(root, height=15, bg='yellow')
listbox.grid(row=1, column=0)

# the Tkinter listbox does not automatically scroll, you need
# to create a vertical scrollbar to the right of the listbox
yscroll = tk.Scrollbar(command=listbox.yview, orient=tk.VERTICAL)
yscroll.grid(row=1, column=1, sticky='n'+'s')
listbox.configure(yscrollcommand=yscroll.set)

cheese_list = [
'Feta', 'Limburger', …
sneekula 969 Nearly a Posting Maven

Here is a comparison of some common Python GUI toolkits. These were created on my Ubuntu/Linux machine, because I could never get PyGTK to go on my Windows Vista machine. I followed the installation routine carefully, but there was always a dll missing, or an entry point wasn't found, or a version missmatch, so I gave up. GTK and PyGTK are more natural on Linux.

Let's take a look at typical PyGTK code:

#!/usr/bin/env python

# display an image using PyGTK + GTK

import pygtk
pygtk.require('2.0')
import gtk

class ShowImage(object):

    def __init__(self):
        # create the main window, and
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        # attach destroy signal to terminate the application
        window.connect("destroy", lambda w: gtk.main_quit())
        window.set_border_width(10)
        window.show()

        # a horizontal box to hold the buttons
        hbox = gtk.HBox()
        hbox.show()
        window.add(hbox)
        
        # pick an image file you have in the working directory, or give
        # the full path, can be a .jpg, .png, ,gif, .bmp image file
        # (filenames are case sensitive on Ubuntu/Linux)
        image_file = "LAKE2.gif"
        image = gtk.Image()
        image.set_from_file(image_file)
        image.show()
        # create a button to contain the image widget
        # auto adjusts to image size
        button = gtk.Button()
        button.add(image)
        button.show()
        hbox.pack_start(button)


ShowImage()
gtk.main()

The same test program using PyQT, PyQT installs easily on Windows and Linux machines:

#!/usr/bin/env python

# display an image using PyQT

import sys
from PyQt4 import QtGui

class MyImage(QtGui.QWidget):
    def __init__(self, parent, width, height):
        QtGui.QWidget.__init__(self, parent)

        # pick an image file you have in the working directory, or give
        # the full path, can …
Nick Evan commented: Good post +17
bumsfeld commented: keep going +11
sneekula 969 Nearly a Posting Maven

The world will end in 2038 when the "real" millenium-bug hits.

The vast majority of embedded systems (which are designed to stay in place for decades) do not use a 64 bit integer to store time (In seconds since the UNIX epoch on 1/1/1970) and will overflow, leading to errors.

The problem is that most of these systems are mission-critical systems usually in an embedded role, meaning it will be hard to rectify this problem.

Most of that stuff will be hopelessly outdated by that time. Maybe a few museum pieces will croak.

cwarn23 commented: good one +0
sneekula 969 Nearly a Posting Maven

Sooner or later some engineers will manage to create a smart robot. Smart enough to consider humans as a pest.

Sulley's Boo commented: your avatar is cute, and so are your thoughts =D +6
sneekula 969 Nearly a Posting Maven

It's time again to poll the well educated folks at DaniWeb about the possible cause of the end of humanity on earth.

sneekula 969 Nearly a Posting Maven

Computers are definitely female, here are the male reasons:
1) Most men who have one don't understand them.
2) Amongst themselves they talk in an incomprehensible language at high speed.
3) You need to tell them every trivial thing you want from them.
4) All of a sudden they refuse to cooperate, and you can't figure out what you did wrong. They refuse to give you any meaningful error message.
5) You always have to buy new stuff for them.
6) If you keep a computer for too long it becomes old and you will constantly wish you could just dump it somewhere.

sneekula 969 Nearly a Posting Maven

If they ask for money up front, then it is most likely a ripoff!