Ene Uran 638 Posting Virtuoso

~S.O.S~ is the best!
Making people have fun and laugh is a real art!

~s.o.s~ commented: Drinking her pretty.... :-) +23
Ene Uran 638 Posting Virtuoso

I am a drinker and have spilled drinks on others. Will I be punished?

Ezzaral commented: heh! +11
Ene Uran 638 Posting Virtuoso

Just noticed that I passed the ever so sweet 1000 postings mark!

Isn't DaniWeb great!

Salem commented: Well done - now you have a gold star as well. +20
Nick Evan commented: Congrats! +8
Ene Uran 638 Posting Virtuoso

To create a window or frame with wxPython you use wx.Frame. There are some basic things you can do with a frame and I tried to put them in one spot:

# a few things you can do with wxPython's wx.Frame
# wx.Frame(parent, id, title, pos, size, style, name)
# set/change colour, cursor, position, size, title, tooltip
# blow the frame to full size and return to normal  

import wx

class MyFrame(wx.Frame):
    """inherits wx.Frame, self is the instance of the frame"""
    def __init__(self):
        # create a frame/window, no parent, default to id=wxID_ANY
        # note that id=wxID_ANY is the same as id=-1 
        # position is overwritten by Center()
        wx.Frame.__init__(self, None, wx.ID_ANY, 'original title', 
            pos=(100, 150), size=(400, 350))
        # show the frame during the creation of the instance
        # default is True, False would hide the frame
        self.Show(True)
        
        # wait just a moment, 4.5 seconds to be exact
        wx.Sleep(4.5)
        
        # this allows you to change the frame title
        self.SetTitle('changed title, colour, and cursor')
        # optionally change the cursor
        self.SetCursor(wx.StockCursor(wx.CURSOR_MAGNIFIER))
        # change the frame's colour 
        # notice British spelling of Colour
        self.SetBackgroundColour('green')
        # now clear old color, set to new color
        self.ClearBackground()
        self.Show()
        
        wx.Sleep(4.5)
        self.SetTitle('center wx.Frame horizontal')
        # optionally center the frame on the display screen
        # notice British spelling of Centre
        # wx.HORIZONTAL, wx.VERTICAL or wx.BOTH (default)
        self.Centre(wx.HORIZONTAL)
        self.Show()
        
        wx.Sleep(4.5)
        cap = 'now center wx.Frame vertical too and change size'
        self.SetTitle(cap)
        #self.Update()
        # change the size of the frame
        width, height = self.GetSize()
        # needs tuple
        self.SetSize((width+200, height-100))
        # in this …
sneekula commented: very nice basics +4
Ene Uran 638 Posting Virtuoso

At least the war on the environment is going well.

Ezzaral commented: ;) +10
Ene Uran 638 Posting Virtuoso

Lawyers have feelings too!

Ene Uran 638 Posting Virtuoso

The information a statusbar can display can come handy:

# set up a customized statusbar with three display fields
# a statusbar is typically an information line at the bottom of a window

import wx
import time

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
        # fill the top part with a panel
        panel = wx.Panel(self, wx.ID_ANY, style=wx.SUNKEN_BORDER)
        panel.SetBackgroundColour("blue")

        self.sb = wx.StatusBar(self, wx.ID_ANY)
        # set the status bar with three fields
        self.sb.SetFieldsCount(3)
        # set an absolute status field width in pixels
        # (negative indicates a variable width field)
        self.sb.SetStatusWidths([-1, -1, -1])
        self.SetStatusBar(self.sb)
        # put some text into field 0 (most left field)
        self.sb.SetStatusText("some text in field 0", 0)
        self.sb.SetStatusText("some text in field 1", 1)

        # use a timer to drive a date/time string in field 3
        # here the most right field of the statusbar
        self.timer = wx.PyTimer(self.onUpdate)
        # update every 1000 milliseconds
        self.timer.Start(1000)
        self.onUpdate()

    def onUpdate(self):
        t = time.localtime(time.time())
        st = time.strftime("%d-%b-%Y   %I:%M:%S", t)
        # put date/time display string into field 2
        self.sb.SetStatusText(st, 2)


app = wx.App(0)
# create a MyFrame instance and show the frame
MyFrame(None, 'test the wx.StatusBar', (460, 300)).Show()
app.MainLoop()
Ene Uran 638 Posting Virtuoso

According to the latest Zogby poll, 10% of Americans are giving President Bush's economic policy the thumbs up.

The other 90% are using a different finger.

Ancient Dragon commented: That's goooood :) +34
Ene Uran 638 Posting Virtuoso

One of the features of Python3 will be that the division operator / will give a float result ( // is used for integer divisions as usual ). You can use this feature now by importing the __future__ module. Test it out with this example:

# access Python3 features like / for float division

from __future__ import division

print "Enter a math statement like 355/113 or (2+3)/2 ..."
while True:
    result = input("Statement: ")
    print result
    if raw_input("Continue? (y, n)").lower() == 'n': break
Ene Uran 638 Posting Virtuoso

Trapping a key event:

# bind keyevent to key down and display the key value

import wx

class KeyEvent(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(400, 70))
        self.SetBackgroundColour("yellow")
        # create a label
        self.label = wx.StaticText(self, wx.ID_ANY, label="  ", pos=(20, 30))

        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)

        self.Show(True)

    def OnKeyDown(self, event):
        keycode = event.GetKeyCode()
        s = "Key value = " + str(keycode)
        self.label.SetLabel(s)
        if keycode == wx.WXK_ESCAPE:
            choice = wx.MessageBox('Are you sure you want to quit? ',
                'Question', wx.YES_NO|wx.CENTRE|wx.NO_DEFAULT, self)
            if choice == wx.YES:
                self.Close()
        event.Skip()


app = wx.App()
KeyEvent(None, wx.ID_ANY, 'press any key (press escape to exit)')
app.MainLoop()
Ene Uran 638 Posting Virtuoso

The wxPython GUI toolkit has a number of ways to specify colors, or should I say colours. Here is a simple example:

# show different ways to specify colours with wxPython

import wx

class ColourTest(wx.Dialog):
    def __init__(self, parent, id, title):
        """use a dialog box as a simple window/frame"""
        wx.Dialog.__init__(self, parent, id, title, size=(300, 300))

        self.pnl1 = wx.Panel(self, -1)
        self.pnl2 = wx.Panel(self, -1)
        self.pnl3 = wx.Panel(self, -1)
        self.pnl4 = wx.Panel(self, -1)
        self.pnl5 = wx.Panel(self, -1)
        self.pnl6 = wx.Panel(self, -1)
        self.pnl7 = wx.Panel(self, -1)
        self.pnl8 = wx.Panel(self, -1)

        # use a wx.GridSizer(rows, cols, vgap, hgap) for layout
        gs = wx.GridSizer(4,2,3,3)
        # for this dialog window wx.EXPAND is not needed
        gs.AddMany([ (self.pnl1, 0 ,wx.EXPAND),
            (self.pnl2, 0, wx.EXPAND),
            (self.pnl3, 0, wx.EXPAND),
            (self.pnl4, 0, wx.EXPAND),
            (self.pnl5, 0, wx.EXPAND),
            (self.pnl6, 0, wx.EXPAND),
            (self.pnl7, 0, wx.EXPAND),
            (self.pnl8, 0, wx.EXPAND) ])

        self.SetSizer(gs)
        self.SetColors()
        self.Centre()
        self.ShowModal()
        self.Destroy()

    def SetColors(self):
        # create a number of colorful panels
        # using different ways to specify colours
        self.pnl1.SetBackgroundColour(wx.BLACK)
        # wx.Colour() uses a (r, g, b) tuple
        self.pnl2.SetBackgroundColour(wx.Colour(139,105,20))
        self.pnl3.SetBackgroundColour(wx.RED)
        # specify as #RRGGBB hex string
        self.pnl4.SetBackgroundColour('#0000FF')
        self.pnl5.SetBackgroundColour('dark green')
        self.pnl6.SetBackgroundColour('midnight blue')
        self.pnl7.SetBackgroundColour(wx.LIGHT_GREY)
        self.pnl8.SetBackgroundColour('plum')


app = wx.App()
ColourTest(None, wx.ID_ANY, 'wxPython colours')
app.MainLoop()
Ene Uran 638 Posting Virtuoso

What I hear, I forget. What I see, I remember. What I do, I understand.
-- Chinese Proverb

techbound commented: Nice chinese proverb! +1
Ene Uran 638 Posting Virtuoso

There is a problem with count() as shown below:

string = "hi"

# test text
text = "hi, I am a history buff with a hideous hidrosis history"

print "Number of '" + string + "' in your file is:", text.count("hi")

"""
my result -->
Number of 'hi' in your file is: 5
"""
Ene Uran 638 Posting Virtuoso

To draw simple shapes like lines, circles, rectangles you have to use the wx.PaintDC surface as the canvas. Here are some basic examples:

# the wx.PaintDC surface is wxPython's canvas
# draw a line on this canvas
# use help(wx.PaintDC) to get more info

import wx

class DrawPanel(wx.Panel):
    """draw a line on a panel's wx.PaintDC surface/canvas"""
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, -1)
        # bind the panel to the paint event
        wx.EVT_PAINT(self, self.onPaint)

    def onPaint(self, event=None):
        # this is the wx drawing surface/canvas
        dc = wx.PaintDC(self)
        dc.Clear()
        # sets pen color and width
        dc.SetPen(wx.Pen("blue", 1))
        x1 = 20
        y1 = 10
        x2 = 500
        y2 = 300
        # draw a line from coordinates (x1,y1) to (x2,y2)
        dc.DrawLine(x1, y1, x2, y2)


app = wx.App()
frame = wx.Frame(None, -1, "Draw a line", size=(550, 350))
dp = DrawPanel(frame)
frame.Show(True)
app.MainLoop()

You can get a little more playful, using just about the same frame work:

# the wx.PaintDC surface is wxPython's canvas
# draw a series of lines on this canvas
# DC stands for Device Context 

import wx

class DrawPanel(wx.Panel):
    """draw lines on a panel's wx.PaintDC surface/canvas"""
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, -1)
        # bind the panel to the paint event
        wx.EVT_PAINT(self, self.onPaint)

    def onPaint(self, event=None):
        # this is the wx drawing surface/canvas
        dc = wx.PaintDC(self)
        dc.Clear()
        # sets pen color and width
        dc.SetPen(wx.Pen("red", 1))
        # set the starting point coordinates to (0,0)
        x1 = y1 = 0
        # use a loop to set the endpoint coordinates (x2,y2)
        # and draw a …
Ene Uran 638 Posting Virtuoso

Here is a templet file that allows you to package your wxPython program to an executable file with the py2exe module. It contains an XML manifest that gives the wxPython widgets a Windows XP appearance on XP machines:

# Py2Exe version 6.6 setup file for wxPython GUI programs.
# Creates a single executable file.
#
# Simply change the filename entry to whatever you called your source file.
# Optionally edit the version info and add the name of your icon file.
# It's easiest to save the modified templet code for instance as
# wx2exe.py to the same folder that containes your source file
# and the optional iconfile like "icon.ico"
#
# Now run the customized wx2exe.py ...
#
# Two subfolders will be created called build and dist.
# The dist folder contains your .exe file, MSVCR71.dll and w9xpopen.exe
# w9xpopen.exe is needed for os.popen() only.
# Your .exe file contains your byte code, all needed modules
# and the Python interpreter.
# The MSVCR71.dll can be distributed, but is often already in
# the Windows system32 folder.
# The build folder is for info only and can be deleted.


from distutils.core import setup
import py2exe
import sys

# Enter the filename of your wxPython source code file to compile.
# Your distribution file will be this filename with a .exe extension.
filename = "wxButton1.py"

# this creates the filename of your .exe file in the dist folder
if filename.endswith(".py"):
    distribution = filename[:-3]
elif filename.endswith(".pyw"):
    distribution …
sneekula commented: works well +4
Ene Uran 638 Posting Virtuoso

Be careful Vernon, fierykido is a psionist and is able to do aerokinesis. He could make the wind around you pretty foul smelling.

Nick Evan commented: Nice :) +6
Salem commented: Yeah, his arguments certainly do "blow" ;) +17
Ene Uran 638 Posting Virtuoso

You can run the command window from python and obtain the results and error messages:

# run DOS cmd.exe from Python code
# works on XP, but may not work on Windows Vista

import subprocess

cmd = "cmd.exe"
command = "dir c:"

p = subprocess.Popen(cmd,
    shell=True,
    #bufsize=1,
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE)

# the \n is important to flush buffer
p.stdin.write("%s\n" % command)

p.stdin.close()
# give it enough time to respond
p.wait()

# optional check (0 = success)
print p.returncode

# read the result to a string
result = p.stdout.read()
print result

# optionally read any error message returned
error = p.stderr.read()
print "error =", error
Ene Uran 638 Posting Virtuoso

A rabbi and a minister were at the neighbourhood picnic. As they rode in one of the boats on the lake, the rabbi stood up, stepped out of the boat, and walked over the water to the nearby stretch of land.

Astonished, the minister decided to see if he could duplicate this miraculous feat. He stepped out of the boat and sank, but managed to swim ashore.

As he stood there drying himself off, the rabbi walked over and said, "Next time ask me first, and I will show you where the rocks are!"

~s.o.s~ commented: Heh. +21
Ene Uran 638 Posting Virtuoso

If electricity comes from electrons, does morality come from morons?

bloody_ninja commented: this is win +1
Ene Uran 638 Posting Virtuoso

If humans ceased to exist then 97 percent of domesticated animals would become extinct within two years.

Ene Uran 638 Posting Virtuoso

I think Tkinter is written in TCL language with a Python wrapper hanging over it. If you want to write a new widget you better learn TCL.

I fooled around a little with the scale widget itself and mouse events and came up with this:

# experiment with Tkinter's Scale widget
# make the slider respond to mouse clicks

import Tkinter as tk

def position(event):
    # let's assume the position is from 0 to 100
    # to match the scales min/max or from_/to value
    position = 100 * event.x/scale_len
    # show result in title bar (test)
    str1 = "position = %d" % position
    root.title(str1)
    # set the slider to the new position
    scale1.set(position)

root = tk.Tk()

scale_lbl = "Click on the scale"
scale_val = tk.IntVar()
scale_len = 300
scale1 = tk.Scale(root, label=scale_lbl, variable=scale_val,
    from_=0, to=100, tickinterval=25, length=scale_len,
    sliderlength=8, orient='horizontal')
scale1.pack(side='left')
scale1.bind("<Button-1>", position)

root.mainloop()

Noticed some strange effect:
keeping the mouse pressed below position 38 inside the dark scale area makes the slider wander lower! Don't ask me why.

Ene Uran 638 Posting Virtuoso

In China a woman gives birth every 2 seconds.

Somebody needs to stop her!

Talking about babies:
The U.S. government prevents parents from giving newborn babies more than nine names.

Ene Uran 638 Posting Virtuoso

I was just having fun dude. Oh well, if you do not like this one, I wouldn't mind. I'm sorry if this one's kinda annoying. :(

No harm intended, just being facetious as usual.

There was this news report that a fellow suffocated from his own rectal exhaust, when he was sleeping in a small tent.

Sulley's Boo commented: :o damn funny, and sad! +4
Ene Uran 638 Posting Virtuoso

An example for how to search a dictionary with key: value pairs for both the value and the key:

# search a dictionary for key or value

def find_key(dic, val):
    """return the key of dictionary dic given the value"""
    return [k for k, v in symbol_dic.iteritems() if v == val][0]

def find_value(dic, key):
    """return the value of dictionary dic given the key"""
    return dic[key]

# test it out
if __name__ == '__main__':
    # dictionary of chemical symbols
    symbol_dic = {
    'C': 'carbon',
    'H': 'hydrogen',
    'N': 'nitrogen',
    'Li': 'lithium',
    'Be': 'beryllium',
    'B': 'boron'
    }

    print find_key(symbol_dic, 'boron')  # B
    print find_value(symbol_dic, 'B')    # boron
Ene Uran 638 Posting Virtuoso

There is no simple dictionary function build in, since values may not be unique, but you can use this:

# search a dictionary for key or value

def find_key(dic, val):
    """return the key of dictionary dic given the value"""
    return [k for k, v in symbol_dic.iteritems() if v == val][0]

def find_value(dic, key):
    """return the value of dictionary dic associated with a given key"""
    return dic[key]

# test it out
if __name__ == '__main__':
    # dictionary of chemical symbols
    symbol_dic = {
    'C': 'carbon',
    'H': 'hydrogen',
    'N': 'nitrogen',
    'Li': 'lithium',
    'Be': 'beryllium',
    'B': 'boron'
    }

    print find_key(symbol_dic, 'boron')  # B
    print find_value(symbol_dic, 'B')    # boron

I used functions for both searches naming them so it's easier to read.

ZZucker commented: nice clean code +1
Ene Uran 638 Posting Virtuoso

Hollywood makes piracy look pretty romantic.

Ene Uran 638 Posting Virtuoso

I would build the world's largest bar.

Ancient Dragon commented: I'll drink to that (hickup!) +21
Ene Uran 638 Posting Virtuoso

A small thread to honor those with creative or simply nice avatars.

I like Sulley's Boo avatar

Sulley's Boo commented: :D +3
Ene Uran 638 Posting Virtuoso

Great, let us know what you like. I still use DrPython for most of my Python programming, but also like PyScripter (gets better all the time, they are still updating).

vegaseat commented: Thanks for coming back! +7
Ene Uran 638 Posting Virtuoso

An old Florida law states that only the missionary position is legal.

I think this is where the missionary is on top and the unchristian is underneath. One way to turn a heathen into a christian.

Ancient Dragon commented: Good observation +20
Ene Uran 638 Posting Virtuoso
# This is text from a file I found.  Write a Python program to
# convert the text into a dictionary with "state": "motto" pairs
# something like {"Alabama": "At Least We're not Mississippi",
# "Alaska": "11,623 Eskimos Can't be Wrong!", ...}
#
# Then write a program that allows you to enter the state and
# it will display the motto of that state.

state_mottos = """\
Alabama:    At Least We're not Mississippi

 Alaska:     11,623 Eskimos Can't be Wrong!

 Arizona     But It's a Dry Heat

 Arkansas:   Litterasy Ain't Everthing

 California: As Seen on TV

 Colorado:   If You Don't Ski, Don't Bother

 Connecticut:  Like Massachusetts, Only Dirtier and with less Character

 Delaware:   We Really Do Like the Chemicals in our Water

 Florida:    Ask Us About Our Grandkids

 Georgia:    We Put the 'Fun' in Fundamentalist Extremism

 Hawaii:     Haka Tiki Mou Sha'ami Leeki Toru (Death to Mainland
             Scum, But Leave Your Money)

 Idaho:      More Than Just Potatoes... Well Okay, Maybe Not, But
             The Potatoes Sure Are Good

 Illinois:   Please Don't Pronounce the "S"

 Indiana:    2 Billion Years Tidal Wave Free

 Iowa:       We Do Amazing Things With Corn

 Kansas:     First Of The Rectangle States

 Kentucky:   Five Million People; Fifteen Last Names

 Louisiana:  We're Not All Drunk Cajun Wackos, But That's Our Tourism Campaign

 Maine:      We're Really Cold, But We Have Cheap Lobster

 Maryland:   A Thinking Man's Delaware

 Massachusetts:    Our Taxes Are Lower Than Sweden's (For Most Tax Brackets)

 Michigan:   First Line of Defense From the Canadians

 Minnesota:  10,000 Lakes and 10,000,000 Mosquitoes …
Ene Uran 638 Posting Virtuoso

Brain:
An enchanting brain has to be capable of a balanced mix of creativity, wit and
understanding. My bosses brain contains the C++ manual in every detail, but
otherwise he is rude and crude and devoid of any people skills. He has a very
ugly wife and three very ugly children. She is a good cook, and they both have
put on weight in places that should prevent the birth of very ugly child number
four.

Beauty/Body:
Women should be cute with fatty tissue properly distributed.

Men should be tall and handsome. If you are the typical out of shape mouse
potato that is standard fare in computer departments, you have to make up for
your deficiency with money, sports car and/or alcohol.

christina>you commented: haha +14
Ene Uran 638 Posting Virtuoso

Spreadsheets are really not that difficult to make with Python. Here is the beginning of a simple Tkinter based spreadsheet program:

# the beginning of a simple Tkinter spreadsheet program
 
import Tkinter as tk
 
root = tk.Tk()
root.title('Tkinter spreadsheet phase 1')
 
def click(event, cell):
    # can do different things with right (3) and left (1) mouse button clicks
    root.title("you clicked mouse button %d in cell %s" % (event.num, cell))
    # test right mouse button for equation solving
    # eg. data = '=9-3' would give 6
    if event.num == 3:
        # entry object in use
        obj = dict[cell]
        # get data in obj
        data = obj.get()
        # if it starts with '=' it's an equation
        if data.startswith('='):
            eq = data.lstrip('=')
            print data, eq
            try:
                # solve the equation
                result = eval(eq)
                #print result, type(result) # test
                # remove equation data
                obj.delete(0, 'end')
                # update cell with equation result
                obj.insert(0, str(result))
            except:
                pass
 
def key_r(event, cell):
    # return/enter has been pressed
    data = dict[cell].get() # get text/data in given cell
    #print cell, dict[cell], data # test
    root.title("cell %s contains %s" % (cell, data))
 
# create a dictionary of key:value pairs
dict = {}
w = 20
h = 1
alpha = ["", 'A', 'B', 'C', 'D', 'E', 'F']
for row in range(5):
    for col in range(5):
        if col == 0:
            # create row labels
            label1 = tk.Label(root, width=3, text=str(row))
            label1.grid(row=row, column=col, padx = 2, pady=2)
        elif row == 0:
            # create column labels
            label1 = tk.Label(root, width=w, text=alpha[col])
            label1.grid(row=row, column=col, padx …
Ene Uran 638 Posting Virtuoso

A couple of things wrong with your countdown timer.
1 - don't limit the size of your root window, widgets won't fit
2 - labels take strings
3 - root.update() is needed
Look this over:

#Gamal Crichton
#Teje's Counter
#04/02/07

from Tkinter import *
import time

class Application(Frame):
    def __init__(self,master,act_name,time_):
        Frame.__init__(self,master)
        self.hh=time_[0]
        self.mm=time_[1]
        self.ss=time_[2]
        self.name=act_name
        self.grid()
        print time_
        self.disp_widgets()
        self.aggregate()
        
        
    def disp_widgets(self):
        #Uses labels to display time.
        Label(self,
              text=self.name, font=("Arial, 32")
              ).grid(row=0,column=0,columnspan=3,sticky=W)
        
        self.hourlbl=Label(self,
              text=str(self.hh), font=("Arial, 40")  # str()!!!!!!!!!!
              )
        self.hourlbl.grid(row=1,column=0,columnspan=1,sticky=W)

        self.minutelbl=Label(self,
              text=str(self.mm), font=("Arial, 40")  # str()!!!!!!!!!!
              )
        self.minutelbl.grid(row=1,column=1,columnspan=1,sticky=W)
        
        self.secondlbl=Label(self,
              text=str(self.ss), font=("Arial, 40")  # str()!!!!!!!!!!
              )
        self.secondlbl.grid(row=1,column=2,columnspan=1,sticky=W)
        
        Button (self,
                text="Stop",
                command=self.show,
                ).grid(row=2,column=0,columnspan=3,sticky=EW)
        
    def show(self):
        # needs more stuff
        print "Booooooooo!"

    def aggregate(self): #This function is supposed to decrement the time
        for hours in range(self.hh, -1, -1):
            for minutes in range(self.mm, -1, -1):
                for seconds in range(self.ss, -1, -1):
                    time.sleep(1)
                    root.update()  # needed!!!!!
                    self.secondlbl["text"]=str(seconds)  # str()!!!!!!!!!! 
                    if self.ss==0:
                        self.ss=60
                self.minutelbl["text"]=str(minutes)  # str()!!!!!!!!!!
                if self.mm==0:
                    self.mm=0
            self.hourlbl["text"]=str(hours)  # str()!!!!!!!!!!

#Main
root=Tk()

root.title("Timer!")

#root.geometry("250x75")  # do not use, too space restrictive!!!

app= Application(root, " Timer ", [2, 4, 5])

root.mainloop()
Ene Uran 638 Posting Virtuoso

Unless you have a huge amount of events in your loop, it could very well be your mouse.

mattyd commented: Tkiner GUI #Always helpful ;) mattyd +3
Ene Uran 638 Posting Virtuoso

So, you want to do a Google search from your Python program, here is the code:

# search Google
 
import webbrowser
 
search_str = raw_input("Enter Google search string: ")
 
# convert to a list and process
qlist = search_str.split(None)
list1 = []
for q in qlist:
    if '+' in q:
        q = q.replace('+', '%2B')
    if ' ' in q:
        q = '"%s"' % q
    q = q.replace(' ', '+')
    list1.append(q)
 
# convert back to a string
query = '+'.join(list1)
url = "http://www.google.com/search?q=%s" % query
 
webbrowser.open(url)
Ene Uran 638 Posting Virtuoso

Ah, the old Turbo C bad habit clrscr() function. First try to make your program without it, it is rarely needed! You can replace one bad habit with another and use:

#include <stdlib.h> 

void clrscr(void)
{
  system ("cls");
  //system ("clear"); // for Unix
}

A more official version of a clrscr() function using Windows API is at:
http://www.daniweb.com/code/snippet232.html

SpS commented: Helps ~~SpS +3
Ene Uran 638 Posting Virtuoso

The Fibonacci series of integers was orignally used in biology to predict the population increase of rodents, or the branching of the veins in a leaf (top to stem).

A Fibonacci number series is made by adding the current number to the previous number to get the next mumber. According to http://en.wikipedia.org/wiki/Fibonacci_number the series starts with 0, 1

This is one of the fastest ways to calculate the Fibonacci series:

def fibo3( n ):
    (current, previous) = (0, 1)
    k = n
    while k > 0:
    # use a tuple swap
        (current, previous) = (previous, current + previous)
    k -= 1
    return current
 
for n in range(13):
    print fibo3(n),
 
"""
example output:
0 1 1 2 3 5 8 13 21 34 55 89 144
"""

This is probably the sweetest way to create a list of the series:

fibo_list = [0,1]
for n in range(input('Enter an integer (>0): ')-1):
    fibo_list.append(fibo_list[-2] + fibo_list[-1])
print fibo_list
 
"""
example output:
Enter an integer (>0): 12
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
"""

Note: changed php code field tags, don't work properly any more.

Ene Uran 638 Posting Virtuoso

Okay, with all that Administrator stuff out of the way let's return to the "Starting Python" sticky.

If you had a list of names with title, first, middle and last name, how would you sort that list by the last name only? Well here is a solution commonly used to sort lists by item or modified item:

# sort a list of names by last name

def sort_names(names):
    """
    sort names by last name, avoiding title, first and middle names
    """
    names_mod = []
    for name in names:
        # split each name into a list
        name_list = name.split()
        # pick the last name from list
        last_name = name_list[-1]
        # create a list of temporary sublists [last_name, name] 
        names_mod.append([last_name, name])
    # sort the modified list of names inplace
    # this will sort by the first item in the 
    # sublists which is last_name
    names_mod.sort()
    # use list comprehension to
    # to remove the temporary last_name item
    return [name[1] for name in names_mod]

names = [
"Dr. Heidi Karin Hirsch",
"Miss Arlene Auerbach",
"Mr. and Mrs. Larry Zoom",
"Mr. Frank Paul Lummer",
"Vicepresident Colter"
]

print "Original list of names:"
for name in names:
    print name

print
print "List of names sorted by last name:"
names_sorted = sort_names(names)
for name in names_sorted:
    print name

"""
output -->
Original list of names:
Dr. Heidi Karin Hirsch
Miss Arlene Auerbach
Mr. and Mrs. Larry Zoom
Mr. Frank Paul Lummer
Vicepresident Colter

List of names sorted by last name:
Miss Arlene Auerbach
Vicepresident …
Ene Uran 638 Posting Virtuoso

Some details on the use of modules in Python, heavily commented. Here is an example of a module:

# modules should be saved to the same folder as the 
# program or to folders listed in sys.path()

# save this module code as apple.py ...
# (module-name and file-name.py have to match, are case sensitive!)

def pieCookingStatus(cooking_time):
    if cooking_time < 35:
        print "Still cooking!"
    elif cooking_time < 40:
        print "Almost done!"
    else:
        print "Take pie out of the oven!"

def piePercentCooked(cooking_time):
    """consider 40 minutes the fully cooked time"""
    return 100 * cooking_time/40

# optional, specify version number of module
version = '1.2'

# this test runs when this code is used as a standalone program, 
# but not as an imported module of another program,
# then the namespace will be apple (name of module) and not __main__
if __name__ == '__main__':
    print "Pie is %d percent cooked." % piePercentCooked(33)
    pieCookingStatus(33)

Now the program that would use the above module:

# test the module apple.py

# import creates a namespace with the module's name (apple)
# also Python creates a precompiled bytecode file apple.pyc for speed
import apple

# optional, check version if it has been specified
if 'version' in dir(apple):
  print 'Version =', apple.version

# optional, show namespaces used
# note that namespace __name__ is assumed for this program
# you don't have to use it, but you have to prefix the 
# modules namespace to functions/variables of the module
# in this case prefix with apple …
Ene Uran 638 Posting Virtuoso

Looks like yo want to open a file called "50" even though the list is all integers.

mattyd commented: Ene Uran is always of Great Help. He\ She should Moderate at DaniWeb! +1
Ene Uran 638 Posting Virtuoso

Here is a simple linear equation solver:

# a Python linear equation solver

def solve(eq, var='x'):
    eq1 = eq.replace("=", "-(") + ")"
    #print eq1   # test
    c = eval(eq1, {var:1j})
    #print c     # test
    return -c.real/c.imag


eq = "x-2 = 2*x"  # example
r = solve(eq)
print "equation: %s\n  result: x = %s" % (eq, r)
Ene Uran 638 Posting Virtuoso

The request came up on the forum for some typical Python class sample code. Here is my nickles worth:

# manage the contents of a basket
# note: 
#   "self" keeps track of instances, here basket1 and basket2
#   it has to be the first argument of a class method/function

class Basket(object):
    """
    a class to add elements to a list and display the result
    default is an empty basket
    """
    def __init__(self, contents=[]):
        # make a true copy of contents list to avoid surprises
        contents = contents[:]
        self.contents = contents

    def add(self, element):
        # add elements to the basket (list)
        self.contents.append(element)
    
    def remove(self, element):
        # remove an element from the basket
        if element in self.contents:
            self.contents.remove(element)
        else:
            print element, " not in basket!"
            
    def print_me(self):
        # print out the list elements as a string
        result = " ".join(self.contents)
        print "Basket now contains:", result


# basket1 instance of the class, it is an empty basket
basket1 = Basket()
# add items to basket1
basket1.add('pins')
basket1.add('needles')
basket1.add('wurst')

# basket2 instance starts out with contents of basket1
# and allows the user to add more elements
basket2 = Basket(basket1.contents)

basket1.print_me()
print "Add things to the basket, use -thing to remove it:"
while True:
    thing = raw_input("Enter a thing (press Enter only to exit): ")
    if thing:
        if thing[0] == '-':
            basket2.remove(thing[1:])
        else:
            basket2.add(thing)
        basket2.print_me()
    else:
        break
    
# final tally, show things now in basket2
print "Final tally:"
basket2.print_me()
Ene Uran 638 Posting Virtuoso

This from the Win32 Programmer's Reference:

The GetPixel function retrieves the red, green, blue (RGB) color value of the pixel at the specified coordinates.

COLORREF GetPixel(

HDC hdc, // handle of device context
int XPos, // x-coordinate of pixel
int nYPos // y-coordinate of pixel
);


Parameters

hdc

Identifies the device context.

nXPos

Specifies the logical x-coordinate of the pixel to be examined.

nYPos

Specifies the logical y-coordinate of the pixel to be examined.

Return Values

If the function succeeds, the return value is an RGB value. If the pixel is outside of the current clipping region, the return value is CLR_INVALID.

Remarks

The pixel must be within the boundaries of the current clipping region.
Not all devices support GetPixel. An application should call GetDeviceCaps to determine whether a specified device supports this function.

A related function SetPixel() is used in one of the C code snippets about plotting. Vegaseat is probably right, for low level things like direct screen access C or C++ is best.

Ene Uran 638 Posting Virtuoso

If you have a Windows machine you can change the frequency and duration:

// simple sounds via Beep(frequency_hrz, duration_ms)
// on the PC internal speaker, a Windows Console program

#include <stdio.h>
#include <windows.h>   // WinApi header file

int main()
{
  puts("using winAPI Beep(frequency_hrz, duration_ms)...");
  Beep(523,500);  // 523 hertz (C5) for 500 milliseconds
  Beep(587,500);
  Beep(659,500);
  Beep(698,500);
  Beep(784,500);
  Sleep(500);    // 500 ms delay
  puts("\n\\a makes a beep on the internal speaker too ...");
  Sleep(500);
  puts("\a");
  Sleep(500);
  puts("\a");
  
  getchar(); // key wait
  return 0;
}
Ene Uran 638 Posting Virtuoso

If you want to use Tkinter to draw some shapes see:
http://www.daniweb.com/techtalkforums/post261377-80.html

If you want to display a GIF image with Tkinter see:
(for other image formats PIL works with Tkinter)
http://www.daniweb.com/code/snippet296.html

If you want to plot a math function you can use VPython:
http://www.daniweb.com/code/snippet376.html

vegaseat commented: very imformative +5
Ene Uran 638 Posting Virtuoso

Here is a small Python program for an online gem store:

# the online gem store

def add2cart(item, amount):
    """build up the cart list"""
    price = amount*list_of_gems[item-1][1]
    cart.append((item-1, amount, price))
    
# list of (gem, price) tuples
list_of_gems = [('ruby', 99.99), ('emerald', 72.50), ('topaz', 23.95), ('agate', 14.00)]

# will be list of (item#, amount, price) tuples
cart = []
# total of all purchases
total = 0

while True:
    print '-'*32, '\n\t\tList of Gems\n', '-'*32
    for k in range(len(list_of_gems)):
        # starts with item_number to enter
        print '%d\t%8s for $%0.2f each' % (k+1, list_of_gems[k][0], list_of_gems[k][1])
    try:
        item = int(raw_input('\nPlease select a gem (by number): '))
        if item > len(list_of_gems):
            print "item number too high! Try again!"
            item = 0
    except ValueError:
        print "Item number not correct! Try again!"
        item = 0
    try:
        if item > 0:
            amount = int(raw_input('Enter quantity of selected item: '))
    except ValueError:
        print "Amount not correct, has to be whole number!  Try again!"
        amount = 0
    if item > 0 and amount > 0:
        add2cart(item, amount)
    else:
        print "Please enter item and amount again!\a\n"
    
    # added .lower() so user can enter 'No' or 'NO' or 'no'
    more = raw_input('Want to buy something else (yes/no)? ').lower()
    # user can enter 'no' or just 'n'
    if 'n' in more:
        print
        print "Thank you for your order, here is your purchase detail:"
        break

print '\n', '~'*38
for x in range(len(cart)):
    item_number = cart[x][0]
    gem = list_of_gems[item_number][0]
    price = list_of_gems[item_number][1]
    quantity = cart[x][1]    
    total_per_item = cart[x][2]
    print '%4d  %8s @ $%0.2f …
vegaseat commented: Practical Stuff! +5
Ene Uran 638 Posting Virtuoso

Its me, Ene,
note that each button ends up executing a function defined in the program. The button uses the command=function statement. The function is activated via its object (ie. just function rng), and not the usual function call (ie. would be rng() ).

Also note that rng is not a keyword, but just a name vegaseat picked for the function he defined earlier. So if you want an RNG going, put it into the function rng() (or whatever you want to name it), then activate it via command=rng.

reRanger commented: Always helpful and nice ;) +1
Ene Uran 638 Posting Virtuoso

I have put together a dictionary of the Morse code:

morseDict = {
'A': '.-',
'B': '-...',
'C': '-.-.',
'D': '-..',
'E': '.',
'F': '..-.',
'G': '--.',
'H': '....',
'I': '..',
'J': '.---',
'K': '-.-',
'L': '.-..',
'M': '--',
'N': '-.',
'O': '---',
'P': '.--.',
'Q': '--.-',
'R': '.-.',
'S': '...',
'T': '-',
'U': '..-',
'V': '...-',
'W': '.--',
'X': '-..-',
'Y': '-.--',
'Z': '--..'
}

# test it
print morseDict

Write a Python program that takes a text string and converts it into a string of Morse code characters separated by a space.

If you have a PC with Windows OS, then you can sound off this string on the internal speaker:

# if you have a computer using Windows you can 
# sound a morse code string off on the internal computer speaker
# using winsound.Beep(frequency-cps, duration-ms)
# you can experiment with tone frequency and duration
import winsound
import time

morseStr = "--.. ..- .-.. ..-"  # ZULU
for c in morseStr:
    print c
    if c == '-':
        winsound.Beep(800, 500)
    elif c == '.':
        winsound.Beep(800, 100)
    else:
        time.sleep(0.4)  # rest between each letter
    time.sleep(0.2)      # rest between each dash/dot

A much more complicated project would be to catch Morse code (microphone?) and convert into an alphabetic string.

Ene Uran 638 Posting Virtuoso

Version 2.5 of Python final release is planned for 12sep2006. It will have a few nice improvements. On of them is class partial. Bumsfeld has talked about adding arguments to GUI callback functions earlier. This new class will help. Here is a fun example that can be used with Python 2.4:

# class partial is similar to currying to add arguments
# starting with Python 2.5 you can simply import class partial
# using: from functools import partial

from Tkinter import Tk, Canvas, Button


class partial(object):
    """partial application using both positional and keyword arguments"""
    def __init__(*args, **kw):
        self = args[0]
        self.fn, self.args, self.kw = (args[1], args[2:], kw)

    def __call__(self, *args, **kw):
        if kw and self.kw:
            d = self.kw.copy()
            d.update(kw)
        else:
            d = kw or self.kw
        return self.fn(*(self.args + args), **d)


root = Tk()
c = Canvas(root,width=200,height=50)
c.pack()

color_list = ['red','blue','green','yellow','black','white']
for color in color_list:
    # uses class partial to construct callbacks for Tkinter widgets
    # called as though it were a function
    # basically passes/implements c.config(bg=color)
    b = Button(root, text=color, command=partial(c.config, bg=color))
    b.pack(side='left')

root.mainloop()

Edit: A correction has been made, in the final production release of Python 2.5 partial() is in module functools.