sneekula 969 Nearly a Posting Maven

Wow and ouch, debasisdas!
Glad you missed that, maybe a paperless society is your goal now?

jephthah commented: ahah +6
sneekula 969 Nearly a Posting Maven

One of your problems is that you named the button and the function the same! Name your button "button_update" or something.

Other problems are the '\' in Label and that name is not assigned a value.

vegaseat commented: nice catch +11
sneekula 969 Nearly a Posting Maven

Want to use a nice file dialog window to open files for your console program? Here is a way:

# use Tkinter's file dialog window to get a file name
# with full path, that you can use in a console program
# askopenfilename() gives one selected filename

# with Python25 use ...
import Tkinter as tk
from tkFileDialog import askopenfilename

# with Python30 use ...
#import tkinter as tk
#from tkinter.filedialog import askopenfilename

root = tk.Tk()
# show askopenfilename dialog without the Tkinter window showing
root.withdraw()

# default is all files
file_name = askopenfilename()

# now you can use the file_name in your program
print(file_name)  # test
sneekula 969 Nearly a Posting Maven

The power drinks that you can get in many stores here can have up to 800 mg caffeine in them, and some students swig down 2 or 3 of those before an exam. That would be the equivalent of 12 - 15 cups of coffee! They fail the exam because their hands get so shaky they can't write.

Like most everything else, taken in moderation coffeine is just fine. BTW, dogs are very sensitive to caffeine, and the caffeine in one cup of coffee, or the theobromine (a compound related to coffeine) in a bar of chocolate is enough to kill a dog.

nav33n commented: Thanks for the info! I didn't know dogs are sensitive to caffeine :) +10
sneekula 969 Nearly a Posting Maven

The Tkinter GUI toolkit does not add a scrollbar to a listbox automagically, you have to do it with a few lines of extra code:

# simple example of a scrollable listbox for Tkinter
# for Python30 use 'import tkinter as tk'

import Tkinter as tk

root = tk.Tk()
root.title('a scrollable listbox')

# create the listbox (height/width in char)
listbox = tk.Listbox(root, width=50, height=6)
listbox.grid(row=0, column=0)

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

# now load the listbox with data
friend_list = [
'Stew', 'Tom', 'Jen', 'Adam', 'Ethel', 'Barb', 'Tiny', 
'Tim', 'Pete', 'Sue', 'Egon', 'Swen', 'Albert']
for item in friend_list:
    # insert each new item to the end of the listbox
    listbox.insert('end', item)

root.mainloop()
sneekula 969 Nearly a Posting Maven

Here is another option to help Python to locate custom modules in custom directories:

If you want to import custom module xyq via the Pythonpath
create a file xyq.pth and stick it into a directory python
will look into, like C:\Python25\Lib\site-packages
The .pth file contains a line showing the directory
in which module xyq is located, for instance:
C:\Python25\Mymodules

lllllIllIlllI commented: Ah beat me to it! :) +2
sneekula 969 Nearly a Posting Maven

A couple were going out for the evening. They were ready, even had the dog put outside. The taxi arrives, and as the couple start out, the dog shoots back in the house. They don’t want the dog shut in the house, so the wife goes out to the taxi while the husband goes into the house again to fetch the dog.

The wife, not wanting it known that the house will be empty explains to the taxi driver: "My husband is just going upstairs to say good-bye to my mother."

A few minutes later, the husband gets into the cab somewhat out of breath.

"Sorry I took so long" he says. "Stupid bitch was hiding under the bed, and I had to poke her with a coat hanger to get her to come out! Then I had to wrap her in a blanket to keep her from scratching and biting me, as I hauled her ass downstairs and tossed her in the back yard! She better not shidd in the vegetable garden either!"

jbennet commented: haha good one +36
Ezzaral commented: hehehe excellent! +19
William Hemsworth commented: haha ;D +9
sneekula 969 Nearly a Posting Maven

Sounds like a real adventure! Hope you don't fall into the rebels' hands or get arrested by the corrupt law enforcers. Don't drink the water!

Ezzaral commented: ! +19
sneekula 969 Nearly a Posting Maven

I assume you mean something simple like this:

# extract the numeric value before the word 'DIFFERENCES'

text = """\
FILE A HAS 2266 LINES OF WHICH 951 WERE IGNORED
FILE B HAS 2193 LINES OF WHICH 878 WERE IGNORED
THERE WERE 2 DIFFERENCES"""

word_list = text.split()
print(word_list)

for ix, word in enumerate(word_list):
    if word.upper() == 'DIFFERENCES':
        # the diff value is just before 'DIFFERENCES'
        diff = int(word_list[ix-1])

print(diff)  # 2
Gribouillis commented: The simpler, the better! +2
sneekula 969 Nearly a Posting Maven

Lots of people eat dog poop and know one knows why.

I don't eat it, and don't know anybody that eats it. I do step in it on occasion, that is disgusting enough!

Gerryx1 commented: Humourous and friendly. +3
sneekula 969 Nearly a Posting Maven

If you watched the response given by the Governor of Louisiana a few days ago, you wonder if there is evolution.

Ancient Dragon commented: LOL I agree :) +36
sneekula 969 Nearly a Posting Maven

This little code creates a list of all the files (full path) in a given directory and any of its subdirectories:

# create a list of all the files in a given direcory
# and any of its subdirectories (Python25 & Python30)

import os

def file_lister(currdir, mylist=[]):
    """
    returns a list of all files in a directory and any of
    its subdirectories
    note that default mylist becomes static
    """
    for file in os.listdir(currdir):
        # add directory to filename
        full_name = os.path.join(currdir, file)  
        if not os.path.isdir(full_name):
            mylist.append(full_name)
        else:
            # recurse into subdirs
            file_lister(full_name)
    return mylist

dir_name = r"C:\Python25\Tools" 
file_list = file_lister(dir_name)
for file in file_list:
    print(file)

"""
my partial output -->
C:\Python25\Tools\i18n\makelocalealias.py
C:\Python25\Tools\i18n\msgfmt.py
C:\Python25\Tools\i18n\pygettext.py
C:\Python25\Tools\pynche\ChipViewer.py
C:\Python25\Tools\pynche\ChipViewer.pyc
C:\Python25\Tools\pynche\ColorDB.py
...
...
"""
sneekula 969 Nearly a Posting Maven

Use something like this that only moves files:

# move files from one directory to another
# if files alrady exist there, they will be overwritten
# retains original file date/time

import os
import shutil

# make sure that these directories exist
dir_src = "C:\\Python25\\ATest1\\"
dir_dst = "C:\\Python25\\ATest2\\" 

for file in os.listdir(dir_src):
    print file  # testing
    src_file = os.path.join(dir_src, file)
    dst_file = os.path.join(dir_dst, file)
    shutil.move(src_file, dst_file)
sneekula 969 Nearly a Posting Maven

Thanks for the lead AD, there are a whole slew of other rather funny banned commercials! I like the girl on the copier.

http://www.youtube.com/watch?v=nI2y4s3vzgk&NR=1

Ancient Dragon commented: LOL :) +36
sneekula 969 Nearly a Posting Maven

I got curious, so I timed the 'just Python' and 'module re' approaches:

# timing characer count by type
# compare 'module re' and 'just Python' approches

import timeit
import re

def count_char1(text):
    """
    count upper case char, lower case char, digits and spaces in a text
    """
    regexes = [ re.compile(x) for x in
        (r"[^A-Z]+", r"[^a-z]+", r"[^0-9]+", r"[^\ ]+")]
    counts = [len(s) for s in (r.sub("", text) for r in regexes)]
    return tuple(counts)

def count_char2(text):
    """
    count upper case char, lower case char, digits and spaces in a text
    """    
    upper = lower = digit = space = 0
    for c in text:
        if c.isupper():
            upper += 1
        elif c.islower():
            lower += 1
        elif c.isdigit():
            digit += 1
        elif c.isspace():
            space += 1
    return (upper, lower, digit, space)


text = """
There is one rule for the industrialist and that is: 
Make the best quality of goods possible at the lowest 
cost possible, paying the highest wages possible.

Henry Ford 1924
"""

# for longer text uncomment line below
#text = text*10

stmt = 'count_char1(text)'
t = timeit.Timer(stmt, setup="from __main__ import count_char1, text")
#  doing 10000 passes * 100 gives the time in microseconds/pass
elapsed = (100 * t.timeit(number=10000))
print( "Function %s takes %0.3f micro-seconds/pass" % (stmt, elapsed) )

stmt = 'count_char2(text)'
t = timeit.Timer(stmt, setup="from __main__ import count_char2, text")
#  doing 10000 passes * 100 gives the time in microseconds/pass
elapsed = (100 * t.timeit(number=10000))
print( "Function %s takes %0.3f micro-seconds/pass" % (stmt, elapsed) )

"""
my …
Gribouillis commented: good idea +2
mn_kthompson commented: Damn fine analysis +2
sneekula 969 Nearly a Posting Maven

The Python function zip() can be used to transpose a twodimensional array (list of lists). The initial result would be a list of tuples, so a list comprehension is used to change the tuples to lists:

# transpose a 2D_array (list of lists) from 4x6 to 6x4

arr_4x6 = [
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0],
[0, 0, 0, 1, 1, 0],
[0, 1, 0, 1, 1, 0],
]

# the * unpacks the array
arr_6x4 = [list(q) for q in zip(*arr_4x6)]

for row in arr_4x6:
    print(row)

print('-'*20)

for row in arr_6x4:
    print(row)

"""
my transpose result -->
[0, 0, 0, 0, 0, 0]
[0, 1, 1, 1, 1, 0]
[0, 0, 0, 1, 1, 0]
[0, 1, 0, 1, 1, 0]
--------------------
[0, 0, 0, 0]
[0, 1, 0, 1]
[0, 1, 0, 0]
[0, 1, 1, 1]
[0, 1, 1, 1]
[0, 0, 0, 0]
"""
sneekula 969 Nearly a Posting Maven

Q: "Why does the law society prohibit sex between lawyers and their clients?"
A: "To prevent clients from being billed twice for essentially the same service."

sneekula 969 Nearly a Posting Maven

Very interesting indeed!

sneekula 969 Nearly a Posting Maven

Here is an example how to use lambda to pass arguments in Tkinter's button command:

import Tkinter as tk

def getCond(par):
    firstCond = par
    #conditions.remove(firstCond)
    print firstCond
    #print conditions


root = tk.Tk()

firstCond = ''

condNames = ['1', '2', '3', '4',  '5', '6']
for item in condNames:
    # use lambda to pass arguments to command-function
    tk.Button(root, text=str(item), command=lambda i=item: getCond(i)).pack()

root.mainloop()

Also, create your function before you call it.

ABMorley commented: Perfect answer +0
sneekula 969 Nearly a Posting Maven

A building full of lawyers was held hostage. The bad guys threatened that, until all their demands were met, they would release one lawyer every hour.

sneekula 969 Nearly a Posting Maven

Just a simple pygame application to show you the basics:

# a simple pygame example
# creates a white circle on a black background
# the event loop makes exit from the program easier

import pygame

pygame.init()

# create a 300 x 300 display window
# the default background is black
win = pygame.display.set_mode((300, 300))

white = (255, 255, 255)
center = (100, 100)
radius = 20
pygame.draw.circle(win, white, center, radius)

# this puts the circle on the display window
pygame.display.flip()

# event loop and exit conditions (windows x click)
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            raise SystemExit
sneekula 969 Nearly a Posting Maven

Re: Why does it make another file with the ending ".Pyc" at the end?

When you saved your class module as awclassPet.py, then Python will also create a compiled bytecode version of this file the first time it is used by an application. The precompiled file awclassPet.pyc will speed things up on reuse. Also notice that module file names are case sensitive.

The variable names you create in main() are local to the function, so you can use the same variable names you use in your class.

You can test your module out with this arrangement:

class Pet:
    def __init__(self,name, an_type, age):
        self.name =  name
        self.an_type = an_type
        self.age = age

    def set_name(self, name):
        self.name = name

    def set_an_type(self, an_type):
        self.an_type = an_type

    def set_age(self, age):
        self.age = age

    def get_name(self):
        return self.name

    def get_an_type(self):
        return self.an_type

    def get_age(self):
        return self.age


# allows you to test the module
# will not be used when the module is imported
if __name__ == '__main__':

    name = "Oscar"
    an_type = "cat"
    age = 13
    
    animals = Pet(name, an_type, age)

    print animals.get_name()
    print animals.get_an_type()
    print animals.get_age()
    print
    
    animals.set_name("Ruby")
    animals.set_an_type("cow")
    animals.set_age(17)
    
    print animals.get_name()
    print animals.get_an_type()
    print animals.get_age()

Tests okay!

I would suggest you write and run your code on an IDE made for Python code, something like IDLE or DrPython. Otherwise your output window will be set to the OS command window colors.

sneekula 969 Nearly a Posting Maven

This simple code shows you the version of Python that is active on your computer:

# show the version of Python installed

import sys

print sys.version
print sys.version[ :3]
sneekula 969 Nearly a Posting Maven

Decorator functions can simplify Python coding, here is an example:

# exploring decorator functions (new since Python24)
# which are higher functions that create new functions
#
# decorator functions are constructed using a function
# within a function (sometimes called wrapper functions)
# when you define a function inside of another function,
# any undefined local variables in the inner function will
# take the value of that variable in the outer function
# snee

def check_num(func):
    """
    a decorator function to check if another 
    function's argument is a number
    """
    def inner(arg):
        # arg is the argument of function func"""
        if type(arg) in (int, float):
            return func(arg)
        else:
            print("need numeric value as argument")
    return inner


# you apply the decorator with prefix @
# directly above the function you want to check
# this is equivalent to print_num = check_num(print_num)
@check_num
def print_num(n):
    print("Number = %s" % n)


# test ...
print_num(7)    # Number = 7
print_num(7.11) # Number = 7.11
print_num('a')  # need numeric value as argument

print('-'*40)

# check alternative approach ...
def print_num2(n):
    print("Number = %s" % n)

print_num2 = check_num(print_num2)

# test ...
print_num2(7)    # Number = 7
print_num2(7.11) # Number = 7.11
print_num2('a')  # need numeric value as argument

I am using the print() function, so it will work with Python25 and Python30.

sneekula 969 Nearly a Posting Maven

The wx.RichTextCtrl() widget allows the user to create formatted text with color, size, font, bullets, images and more:

# experiment with wxPython's
# wx.RichTextCtrl(parent, id, value, pos, size, style=wx.RE_MULTILINE, 
#    validator, name)
# allows you to create formatted text with color, size, font, images ...
# snee

import wx
import wx.richtext

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
        self.SetBackgroundColour("white")
        
        self.rich = wx.richtext.RichTextCtrl(self, wx.ID_ANY, value="")
        self.rich.WriteText("Default is black text.\n")
        self.rich.BeginBold()
        self.rich.WriteText("Write this text in bold")
        self.rich.BeginTextColour('red')
        self.rich.WriteText(" and this text in bold and red.\n")
        self.rich.EndTextColour()
        self.rich.EndBold()
        
        self.rich.BeginFontSize(30)
        self.rich.WriteText("This text has point size 30\n")
        self.rich.EndFontSize()
        
        font = wx.Font(16, wx.SCRIPT, wx.NORMAL, wx.LIGHT)
        self.rich.BeginFont(font)
        self.rich.WriteText("This text has a different font\n")
        self.rich.EndFont()
        self.rich.Newline()
        # indent the next items 100 units (tenths of a millimeter)
        self.rich.BeginLeftIndent(100) 
        
        # insert an image you have in the work directory
        # or give the full path, can be .bmp .gif .png .jpg
        image_file = "Duck2.jpg"
        image= wx.Image(image_file, wx.BITMAP_TYPE_ANY)
        # wx.BITMAP_TYPE_ANY   tries to autodetect the format
        self.rich.WriteImage(image)
        self.rich.Newline()
        self.rich.EndLeftIndent()
        

app = wx.App()
mytitle = 'testing wx.RichTextCtrl'
width = 560
height = 400
# create the MyFrame instance and show the frame
MyFrame(None, mytitle, (width, height)).Show()
app.MainLoop()
sneekula 969 Nearly a Posting Maven

My father owns a lot of tobacco stock, please don't quit smoking!

~s.o.s~ commented: Haha, nice one. +26
sneekula 969 Nearly a Posting Maven

Obama makes me angry.
Hope he doesn't screw this country up.

Oh well!

It would be very hard to screw it up any worse than Bush.

Ezzaral commented: Definitely. +13
sneekula 969 Nearly a Posting Maven

You pay 2 Dollars and you are allowed to throw 4 dice. If the sum of the dice is less than 9, you win 12 Dollars, otherwise you lose your investment. Should you play this game?

Let a small Python program help you.

sneekula 969 Nearly a Posting Maven

Any fool can paint a picture, but it takes a wise man to be able to sell it.

Shanti C commented: smart quote +2
sneekula 969 Nearly a Posting Maven

Oh sweet Jesus! Years ago they used to pester us with stuff like this. C syntax can be real ugly, and your example is one of the best examples of ugly C syntax.

tyincali commented: I concur +1
sneekula 969 Nearly a Posting Maven

cant wait until 66,666 lol

You are almost there!

~s.o.s~ commented: Like they all say; LOL :-) +23
sneekula 969 Nearly a Posting Maven

Here is one approach to a rock, paper and scissors game in console format:

# Rock, paper and scissors game ...

import random

def game(you):
    """
    returns draw, win or lose in message string
    """
    # pick the computer hand
    comp = random.choice(hand)
    # determine the winner
    if you == comp:
        return "You %s and computer %s result is a draw!" % (you, comp)
    elif you == "rock" and comp == "scissors":
        return "You %s and computer %s you win!" % (you, comp)
    elif you == "paper" and comp == "rock":
        return "You %s and computer %s you win!" % (you, comp)
    elif you == "paper" and comp == "scissors":
        return "You %s and computer %s you lose!" % (you, comp)
    elif you == "rock" and comp == "paper":
        return "You %s and computer %s you lose!" % (you, comp)
    elif you == "scissors" and comp == "paper":
        return "You %s and computer %s you win!" % (you, comp)
    elif you == "scissors" and comp == "rock":
        return "You %s and computer %s you lose!" % (you, comp)
    else:
        return ""

print "Rock, paper and scissors game by ... "
print
print "Options:"
print "1  rock"
print "2  paper"
print "3  scissors"
print "4  random"
print "5  exit"
print

hand = ["rock", "paper", "scissors"]
win = 0
lose = 0
draw = 0
result = ""
while True:
    try:
        opt = int(raw_input("Enter your option number ( 1- 5): "))
    except:
        opt = 4  # default on error is random …
sneekula 969 Nearly a Posting Maven

Something simple for a change, some Python code to use Newton's method to approximate a square root:

# use Newton's method to get the square root of a
a = 144

# any initial approximation
x = 4.0
while True:
    print x
    # Newton's square root approximation
    y = (x + a/x) / 2
    # with floats it's safer to compute the absolute value
    # of the difference between them rather then using y == x
    # make delta something small
    delta = 0.000000001
    if abs(y - x) < delta:
        break
    # now asign y to x and go again
    # the approximation gets closer with every loop
    x = y

"""
my output --->
4.0
20.0
13.6
12.0941176471
12.0003662165
12.0000000056
12.0
"""
sneekula 969 Nearly a Posting Maven
Ancient Dragon commented: great stuff :) +36
sneekula 969 Nearly a Posting Maven

Drinking a bottle of beer a day helps to reduce the chance of kidney stones by 40%.

Nick Evan commented: hooray! +10
sneekula 969 Nearly a Posting Maven

Scientific American Magazine
A Solar Grand Plan
http://www.sciam.com/article.cfm?id=a-solar-grand-plan

Solar power plants could supply 69 percent of the U.S.’s electricity and 35 percent of its total energy by 2050. Excess daytime energy would be stored as compressed air in underground caverns to be tapped during nighttime hours.

Salem commented: #46 :D +21
sneekula 969 Nearly a Posting Maven

You might want to be sure the front side is a match to what the backside presages.

Correct! You won the door price!

Q: "Why do cemeteries have fences around them?"
A: "ni teg ot gniyd era elpoep esuaceb"

~s.o.s~ commented: The best question of the day so far! +23
sneekula 969 Nearly a Posting Maven

Typical official communications between Canadians and their neighbours to the South.

Americans: "Please divert your course 15 degrees to the north to avoid a collision."

Canadians: "Recommend you divert YOUR course 15 degrees to the south to avoid a collision."

Americans: "This is the captain of a US Navy ship. I say again, divert YOUR course."

Canadians: "No, I say again, divert YOUR course."

Americans: "This is the aircraft carrier USS Missouri. We are a large warship of the US Navy. DIVERT YOUR COURSE *NOW*."

Canadians: "We are a lighthouse. Your call."

Ancient Dragon commented: LOL I liked that one :) Although Canadians are also Americans. +36
sneekula 969 Nearly a Posting Maven

Q: "What did the blond fellow say after reading the buxom waitress' name tag?"
A: " 'Debbie' ... that's cute. What did you name the other one?''

sittas87 commented: lol. Gotcha +3
sneekula 969 Nearly a Posting Maven

I was trying to create an alternative calculator using some of wxPython's input widgets like wx.Choice and wx.TextCtrl. This turned out to be a good example for the wx.GridBagSizer too. The basic workings are there, but as always there is room for improvement:

# do some simple math operations with
# wx.Choice(parent,id,pos,size,choices,style)

import wx
from math import *

class MyFrame(wx.Frame):
    def __init__(self, parent, title, operation_list):
        wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(350, 270))
        self.SetBackgroundColour('green')

        # create choice widget for the math operations
        self.choice = wx.Choice(self, wx.ID_ANY, choices=operation_list)
        # select item 0 (first item) in choices list to show
        self.choice.SetSelection(0)
        self.choice.SetToolTip(wx.ToolTip('select one math operation'))
        # bind the checkbox events to action
        self.choice.Bind(wx.EVT_CHOICE, self.onAction)
        
        edit_label1 = wx.StaticText(self, wx.ID_ANY, 'enter x')
        self.edit1 = wx.TextCtrl(self, wx.ID_ANY, value="1",
            size=(200, 20))
        
        edit_label2 = wx.StaticText(self, wx.ID_ANY, 'enter y')
        self.edit2 = wx.TextCtrl(self, wx.ID_ANY, value="1",
            size=(200, 20))
            
        edit_label3 = wx.StaticText(self, wx.ID_ANY, 'result')
        self.edit3 = wx.TextCtrl(self, wx.ID_ANY, value="",
            size=(200, 20))
        self.edit3.SetToolTip(wx.ToolTip('double click to move data to x'))
        self.edit3.Bind(wx.EVT_LEFT_DCLICK, self.onDoubleClick)
        
        self.button = wx.Button(self, wx.ID_ANY, label='Calculate')
        # bind mouse event to action
        self.button.Bind(wx.EVT_BUTTON, self.onAction)
        
        # hgap is between columns, vgap between rows
        sizer = wx.GridBagSizer(vgap=0, hgap=0)
        # pos=(row, column)
        sizer.Add(edit_label1, pos=(0,0), flag=wx.ALL|wx.EXPAND, border=10)
        sizer.Add(self.edit1, pos=(0,1), flag=wx.ALL|wx.EXPAND, border=10)
        sizer.Add(edit_label2, pos=(1,0), flag=wx.ALL|wx.EXPAND, border=10)
        sizer.Add(self.edit2, pos=(1,1), flag=wx.ALL|wx.EXPAND, border=10)
        # span=(rowspan, columnspan)
        sizer.Add(self.choice, pos=(2,0), span=(1, 2),
            flag=wx.ALL|wx.EXPAND, border=10)
        sizer.Add(self.button, pos=(3,0), span=(1, 2),
            flag=wx.ALL|wx.EXPAND, border=10)
        sizer.Add(edit_label3, pos=(4,0), flag=wx.ALL|wx.EXPAND, border=10)
        sizer.Add(self.edit3, pos=(4,1), flag=wx.ALL|wx.EXPAND, border=10)
        self.SetSizerAndFit(sizer)

    def onAction(self, event):
        op = self.choice.GetStringSelection()
        x = float(self.edit1.GetValue())
        y = float(self.edit2.GetValue())
        if y == 0.0 and op == 'x / y' :
            result …
vegaseat commented: nice code snee +9
sneekula 969 Nearly a Posting Maven

Did you hear about the welfare doll?

You wind it up and it doesn't work.

R0bb0b commented: LOL :) +2
sneekula 969 Nearly a Posting Maven

Oh the pain of "gorilla arm", looks like the medical profession will rake in the money more than ever.

Microsoft has to copy someone elses idea, this time it's the iPhone?

sneekula 969 Nearly a Posting Maven

Do you know the problem with lawyer jokes?

Lawyers don't think they're funny, and the rest of us don't think they're jokes!

sneekula 969 Nearly a Posting Maven

Add the line
number1 = number2 = number3 = number4 = number5 = number6 = 0
right below the line
counter = counter +1

This way your line 64 does not mix up the possible answers and Python knows about all the variables used in that line.

leegeorg07 commented: v helpful +1
sneekula 969 Nearly a Posting Maven

If a man makes three correct consecutive guesses, does that make him an expert?

scru commented: haha +3
sneekula 969 Nearly a Posting Maven

A nice looking informative about-box is easy to achieve with the wx.AboutBox() widget. The example also touches on menu construction and wxPython's wordwrap feature:

# testing the fancy wx.AboutBox() widget

import wx
from wx.lib.wordwrap import wordwrap

class MyFrame(wx.Frame):
    """
    create a frame, with a menu, statusbar and 2 about dialogs
    """
    def __init__(self):
        # create a frame/window, no parent, default to wxID_ANY
        wx.Frame.__init__(self, None, wx.ID_ANY, "wx.AboutBox test",
            pos=(300, 150), size=(300, 350))
        self.SetBackgroundColour("brown")

        # create a status bar at the bottom
        self.CreateStatusBar()
        self.SetStatusText("Click on File")

        menu = wx.Menu()
        # the optional & allows you to use alt/a
        # the last string argument shows in the status bar on mouse_over
        menu_about = menu.Append(wx.ID_ANY, "&About", "Ho-hum about box")
        menu_about2 = menu.Append(wx.ID_ANY, "About&2", "Fancy about box")
        menu.AppendSeparator()
        # the optional & allows you to use alt/x
        menu_exit = menu.Append(wx.ID_ANY, "E&xit", "Quit the program")

        # create a menu bar at the top
        menuBar = wx.MenuBar()
        # the & allows you to use alt/f
        menuBar.Append(menu, "&File")
        self.SetMenuBar(menuBar)

        # bind the menu events to an action/function/method
        self.Bind(wx.EVT_MENU, self.onMenuAbout, menu_about)
        self.Bind(wx.EVT_MENU, self.onMenuAbout2, menu_about2)
        self.Bind(wx.EVT_MENU, self.onMenuExit, menu_exit)

    def onMenuAbout(self, event):
        """a somewhat ho-hum about box"""
        dlg = wx.MessageDialog(self,
            "a simple application using wxFrame, wxMenu\n"
            "a statusbar, and this about message.",
            "About", wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()

    def onMenuAbout2(self, event):
        """use the much fancier wx.AboutBox()"""
        # first fill the info object
        info = wx.AboutDialogInfo()
        info.Name = "Bratwurst7"
        info.Version = "v.1.7.4"
        info.Copyright = "(C) copyfight 2008"
        info.Description = wordwrap(
            "The Bratwurst7 program is a software program that "
            "makes you …
sneekula 969 Nearly a Posting Maven

I was playing around with wxPython's slider widget and found a nice application for it:

# use slider inputs to calculate cost of petrol in the USA and Europe

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
        self.SetBackgroundColour("yellow")

        # create input widgets
        # label for slider1
        label_s1 = wx.StaticText(self, wx.ID_ANY, "US cents per US Gallon:")
        # can only use integer values!!!
        # initial value = 450, min value = 300, max value = 600
        self.slider1 = wx.Slider(self, wx.ID_ANY, 450, 300, 600, size=(320, 40),
            style=wx.SL_HORIZONTAL|wx.SL_LABELS)
        # label for slider2
        label_s2 = wx.StaticText(self, wx.ID_ANY, "Euro cents per Liter:")
        # initial value = 150, min value = 100, max value = 200
        self.slider2 = wx.Slider(self, wx.ID_ANY, 150, 100, 200, size=(320, 40),
            style=wx.SL_HORIZONTAL|wx.SL_LABELS)
        # label for slider3
        label_s3 = wx.StaticText(self, wx.ID_ANY, "US cents per Euro:")
        # initial value = 160, min value = 100, max value = 200
        self.slider3 = wx.Slider(self, wx.ID_ANY, 160, 100, 200, size=(320, 40),
            style=wx.SL_HORIZONTAL|wx.SL_LABELS)

        # bind all mouse slider marker drags to the same action
        self.Bind(wx.EVT_SLIDER, self.onAction)

        # create an output widget
        self.label = wx.StaticText(self, wx.ID_ANY, "")

        # use a vertical boxsizer for the widget placement
        sizer_v = wx.BoxSizer(wx.VERTICAL)
        sizer_v.Add(label_s1, 0, flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=10)
        sizer_v.Add(self.slider1, 0, flag=wx.ALL|wx.EXPAND, border=5)
        sizer_v.Add(label_s2, 0, flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=10)
        sizer_v.Add(self.slider2, 0, flag=wx.ALL|wx.EXPAND, border=5)
        sizer_v.Add(label_s3, 0, flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=10)
        sizer_v.Add(self.slider3, 0, flag=wx.ALL|wx.EXPAND, border=5)
        sizer_v.Add(self.label, 0, flag=wx.ALL|wx.EXPAND, border=10)
        self.SetSizer(sizer_v)

        # show opening result
        self.onAction(None)

    def onAction(self, event):
        """ some action code"""
        s = "The result ... \n\n"
        # gives integer cents values, convert to …
sneekula 969 Nearly a Posting Maven

You can input a date the graphical way, let's call it the wxPythonian way, with a simple mouse point and click:

# explore the wx.calendar.CalendarCtrl() control
# allows for point and click date input

import wx
import wx.calendar as cal

class MyCalendar(wx.Dialog):
    """create a simple dialog window with a calendar display"""
    def __init__(self, parent, mytitle):
        wx.Dialog.__init__(self, parent, wx.ID_ANY, mytitle)
        # use a box sizer to position controls vertically
        vbox = wx.BoxSizer(wx.VERTICAL)

        # wx.DateTime_Now() sets calendar to current date
        self.calendar = cal.CalendarCtrl(self, wx.ID_ANY, wx.DateTime_Now())
        vbox.Add(self.calendar, 0, wx.EXPAND|wx.ALL, border=20)
        # click on day
        self.calendar.Bind(cal.EVT_CALENDAR_DAY, self.onCalSelected)
        # change month
        self.calendar.Bind(cal.EVT_CALENDAR_MONTH, self.onCalSelected)
        # change year
        self.calendar.Bind(cal.EVT_CALENDAR_YEAR, self.onCalSelected)

        self.label = wx.StaticText(self, wx.ID_ANY, 'click on a day')
        vbox.Add(self.label, 0, wx.EXPAND|wx.ALL, border=20)

        button = wx.Button(self, wx.ID_ANY, 'Exit')
        vbox.Add(button, 0, wx.ALL|wx.ALIGN_CENTER, border=20)
        self.Bind(wx.EVT_BUTTON, self.onQuit, button)

        self.SetSizerAndFit(vbox)
        self.Show(True)
        self.Centre()

    def onCalSelected(self, event):
        #date = event.GetDate()
        date = self.calendar.GetDate()
        day = date.GetDay()
        # for some strange reason month starts with zero
        month = date.GetMonth() + 1
        # year is yyyy format
        year = date.GetYear()
        s1 = "%02d/%02d/%d \n" % (month, day, year)
        # or just take a slice of the first 8 characters to show mm/dd/yy
        s2 = str(date)[0:8]
        self.label.SetLabel(s1 + s2)

    def onQuit(self, event):
        self.Destroy()


app = wx.App()
MyCalendar(None, 'wx.calendar.CalendarCtrl()')
app.MainLoop()
sneekula 969 Nearly a Posting Maven

This code sample shows you how to add an about message box to your wxPython program:

# wxPython Frame with menu, statusbar, and about dialog

import wx

class MyFrame(wx.Frame):
    """
    create a frame, with menu, statusbar and about dialog
    inherits wx.Frame
    """
    def __init__(self):
        # create a frame/window, no parent, default to wxID_ANY
        wx.Frame.__init__(self, None, wx.ID_ANY, 'About (click File)',
            pos=(300, 150), size=(300, 350))

        # create a status bar at the bottom
        self.CreateStatusBar()
        self.SetStatusText("This is the statusbar")

        menu = wx.Menu()
        # the optional & allows you to use alt/a
        # the last string argument shows in the status bar on mouse_over
        menu_about = menu.Append(wx.ID_ANY, "&About", "About message")
        menu.AppendSeparator()
        # the optional & allows you to use alt/x
        menu_exit = menu.Append(wx.ID_ANY, "E&xit", "Quit the program")

        # create a menu bar at the top
        menuBar = wx.MenuBar()
        # the & allows you to use alt/f
        menuBar.Append(menu, "&File")
        self.SetMenuBar(menuBar)

        # bind the menu events to an action/function/method
        self.Bind(wx.EVT_MENU, self.onMenuAbout, menu_about)
        self.Bind(wx.EVT_MENU, self.onMenuExit, menu_exit)

    def onMenuAbout(self, event):
        dlg = wx.MessageDialog(self,
            "a simple application using wxFrame, wxMenu\n"
            "a statusbar, and this about message.  snee",
            "About", wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()

    def onMenuExit(self, event):
        # via wx.EVT_CLOSE event
        self.Close(True)

app = wx.App(0)
# create class instance
window = MyFrame()
window.Show(True)
# start the event loop
app.MainLoop()
sneekula 969 Nearly a Posting Maven

The wxPython GUI toolkit has some interesting widgets, one of them is a complete analog clock widget. Here is an example:

# looking at the wxPython analog clock widget

import wx
from wx.lib import analogclock as ac

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)

        clock = ac.AnalogClockWindow(self)
        clock.SetBackgroundColour('gray')
        clock.SetHandColours('black')
        clock.SetTickColours('WHITE')
        # set hour and minute ticks
        clock.SetTickSizes(h=15, m=5)
        # set hour style
        clock.SetTickStyles(ac.TICKS_ROMAN)
        self.SetSize((400,350))


app = wx.App()
frame = MyFrame(None, wx.ID_ANY, "analogclock")
frame.Show()
app.MainLoop()