sneekula 969 Nearly a Posting Maven

Mixing tabs and spaces will give you very troublesome indentations. I recommend to stick with spaces only, since not everyone's tab settings are the same.

Somewhere in your program you have to get a value for image_name before you call your function.

sneekula 969 Nearly a Posting Maven

To colorize words you are asking too much of good old Tkinter. You most likely need to got with the wx.StyledTextCtrl() widget.
This STC control wraps the Scintilla editor component so it will work with wxPython. Could be that something like this is available for Tlinter.

How about IDLE, that's written using the Tkinter GUI toolkit.

sneekula 969 Nearly a Posting Maven

Looking through IDLE's source code (should be right on your drive) might give you some insight into code highlighting.

sneekula 969 Nearly a Posting Maven

Our Python friend leegeorg07 just pointed out a good tutorial site at:
http://www.sthurlow.com/python/

sneekula 969 Nearly a Posting Maven

nothing against zetlins first reply but he did just copy that from the tutorial from here

He should have given some credit to the original source.

Reminds me of a quote from Albert Einstein:

Plagiarism is stealing from one source.
Research is stealing from many sources
.

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

Don't forget Danieb's very own "Starting Python" at:
http://www.daniweb.com/forums/thread20774.html

You can find some helpful talk, code samples and hints.

sneekula 969 Nearly a Posting Maven

Using the wx.ToggleButton to play with wxPython's colours:

# testing the wxPython widgets ...
# wx.ToggleButton(parent, id, label, pos, size, style)
# wx.Dialog(parent, id, title, pos, size, style)
# note: id wx.ID_ANY is the same as -1
# also: if a button stays toggled the colours will mix

import wx

class MyDialog(wx.Dialog):
    def __init__(self, parent, mytitle):
        # use a simple dialog box rather than a frame
        wx.Dialog.__init__(self, parent, wx.ID_ANY, mytitle, 
            size=(300, 200))

        # wx.Colour(red, green, blue, alpha=wx.ALPHA_OPAQUE)
        # r, g, or b colour intensity can be 0 to 255
        self.colour = wx.Colour(0, 0, 0)  # black
        #print str(self.colour)  # (0, 0, 0, 255)

        tb1 = wx.ToggleButton(self, wx.ID_ANY, 'red', pos=(20, 20))
        tb2 = wx.ToggleButton(self, wx.ID_ANY, 'green', pos=(20, 60))
        tb3 = wx.ToggleButton(self, wx.ID_ANY, 'blue', pos=(20, 100))

        self.panel  = wx.Panel(self, wx.ID_ANY, pos=(150, 20), 
            size=(110, 110), style=wx.SUNKEN_BORDER)
        self.panel.SetBackgroundColour('black')

        self.Bind(wx.EVT_TOGGLEBUTTON, self.ToggleRed, tb1)
        self.Bind(wx.EVT_TOGGLEBUTTON, self.ToggleGreen, tb2)
        self.Bind(wx.EVT_TOGGLEBUTTON, self.ToggleBlue, tb3)
        
        # create a label to show result
        self.label = wx.StaticText(self, wx.ID_ANY, "click a button",
            pos=(20, 140))

        self.Centre()
        self.ShowModal()
        self.Destroy()

    def ToggleRed(self, event):
        green = self.colour.Green()
        blue = self.colour.Blue()
        if  self.colour.Red():
            self.colour.Set(0, green, blue)
        else:
            self.colour.Set(255, green, blue)
        self.panel.SetBackgroundColour(self.colour)
        # clear old colour, set to new colour
        self.panel.ClearBackground()
        s = self.colour.GetAsString()
        self.label.SetLabel(s)

    def ToggleGreen(self, event):
        red = self.colour.Red()
        blue = self.colour.Blue()
        if  self.colour.Green():
            self.colour.Set(red, 0, blue)
        else:
            self.colour.Set(red, 255, blue)
        self.panel.SetBackgroundColour(self.colour)
        self.panel.ClearBackground()
        s = self.colour.GetAsString()
        self.label.SetLabel(s)

    def ToggleBlue(self, event):
        red = self.colour.Red()
        green = self.colour.Green()
        if  self.colour.Blue():
            self.colour.Set(red, green, 0)
        else:
            self.colour.Set(red, green, 255)
        self.panel.SetBackgroundColour(self.colour)
        self.panel.ClearBackground()
        s = self.colour.GetAsString()
        self.label.SetLabel(s)


app = wx.App(0)
MyDialog(None, 'wx.ToggleButton()')
app.MainLoop()

Also …

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

Spelling a string in reverse the old fashioned way is always a good exercise in any computer language.

Here is an example in C language:

// spell a text string forward and backward

#include <stdio.h>

int main(void)
{
  char text[80];
  int k;

  strcpy(text, "Spell this string forward then backward");
  printf("String = %s \n", text);

  // forward spelling puts a space between characters
  for(k = 0; k < strlen(text); k++)
    printf("%c ", text[k]);
  printf("\n\n");

  // now the reverse spelling
  for(k = strlen(text)-1; k >= 0; k--)
    printf("%c ", text[k]);
    
  getchar();  // wait
}

This would be its Python language counter part:

text = "Spell this string forward then backward"
print text

# as you spell forward the comma puts a space between characters
for c in text:
    print c,

print "\n"

# now the reverse spelling
for c in reversed(text):
    print c,

raw_input()  # wait
sneekula 969 Nearly a Posting Maven

Man, you should visit London for excursion on church conversions...
I know at least 10 in my closes area

I know people have turned some of the smaller churches into interesting homes for themselves.

sneekula 969 Nearly a Posting Maven

I took the idea of multiple buttons layout from vegaseat's little wxPython calculator ( http://www.daniweb.com/forums/post648463-31.html ) and applied it to form a periodic table. You can easily expand the element dictionary to pack more practical information into this program:

# create a Periodic Table with multiple wxButton() widgets

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, list_pt1, list_pt2):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, pos=(0,20),
        size=(640, 330))
        self.SetBackgroundColour('green')

        # main sizer
        vsizer = wx.BoxSizer(wx.VERTICAL)

        # wx.GridSizer(rows, cols, vgap, hgap)
        # sizer for standard periodic table elements
        gsizer1 = wx.GridSizer(8, 18)

        font = wx.Font(10, wx.MODERN, wx.NORMAL, wx.BOLD)
        self.buttons1 = []
        for ix, symbol in enumerate(list_pt1):
            # forms a list of button objects, make certain id is unique
            btn_id = 100 + ix
            label = symbol
            self.buttons1.append(wx.Button(self, btn_id, label))
            self.Bind(wx.EVT_BUTTON, self.clickedButton, id=btn_id)
            self.buttons1[ix].SetFont(font)
            if symbol == " ":
                self.buttons1[ix].SetBackgroundColour("green")
            else:
                self.buttons1[ix].SetBackgroundColour("yellow")
            # the gridsizer fills left to right one row at a time
            gsizer1.Add(self.buttons1[ix], 0, wx.ALL|wx.EXPAND, border=1)

        # sizer for Lanthanides and Actinides
        gsizer2 = wx.GridSizer(3, 15)

        self.buttons2 = []
        for ix, symbol in enumerate(list_pt2):
            # forms a list of button objects, make certain id is unique
            btn_id = 300 + ix
            label = symbol
            #print label, ix, btn_id  # testing
            self.buttons2.append(wx.Button(self, btn_id, label))
            self.Bind(wx.EVT_BUTTON, self.clickedButton, id=btn_id)
            self.buttons2[ix].SetFont(font)
            self.buttons2[ix].SetBackgroundColour("pink")
            self.buttons2[ix].ClearBackground()
            # the gridsizer fills left to right one row at a time
            gsizer2.Add(self.buttons2[ix], 0, wx.ALL|wx.EXPAND, border=1)

        vsizer.Add(gsizer1, 0, wx.EXPAND)
        # spacer
        vsizer.Add((0, 30), 0, wx.EXPAND)
        vsizer.Add(gsizer2, 0, wx.EXPAND)
        #self.SetSizerAndFit(vsizer)
        self.SetSizer(vsizer)

    def clickedButton(self, event):
        # get the event id and then the …
sneekula 969 Nearly a Posting Maven

The wx.grid.Grid() widget lets you present tabular data in an organized fashion, very similar to the popular spreadsheet programs. Here is a short example of it's use:

# a practical use of wxPython's wx.grid.Grid() widget
# load the grid via a list of lists
# bind cell select (mouse left click)

import wx
import wx.grid

class MyGrid(wx.grid.Grid):
    def __init__(self, parent, data_list):
        wx.grid.Grid.__init__(self, parent, wx.ID_ANY)
        self.parent = parent

        # set the rows and columns the grid needs
        self.rows = len(data_list)
        self.cols = len(data_list[0])
        self.CreateGrid(self.rows, self.cols)

        # set some column widths (default is 80) different
        self.SetColSize(0, 180)
        self.SetColSize(3, 100)
        self.SetRowLabelSize(40)  # sets leading row width

        # set column lable titles at the top
        for ix, title in enumerate(data_list[0]):
            self.SetColLabelValue(ix, title)

        # create reusable attribute objects
        self.attr = wx.grid.GridCellAttr()
        self.attr.SetTextColour('black')
        self.attr.SetBackgroundColour('yellow')
        #self.attr.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL))

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

        self.loadCells(data_list)

    def onCellLeftClick(self, event):
        row = event.GetRow()
        col = event.GetCol()
        self.parent.SetTitle("row=%d  col=%d  value=%s" %
            (row, col, self.GetCellValue(row, col)))
        # move the grid's cursor to frame the cell
        self.SetGridCursor(row, col)

    def loadCells(self, data_list):
        # note that title row is taken
        for row in range(1, self.rows):
            # set cell attributes for the whole row
            self.SetRowAttr(row-1, self.attr)
            for col in range(self.cols):
                value = data_list[row][col]
                self.SetCellValue(row-1, col, value)
                self.SetReadOnly(row-1, col, True)
                if col > 0:
                    self.SetCellAlignment(row-1, col,
                        wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)

        self.SetCellTextColour(row, 0, 'red')
        self.SetCellBackgroundColour(row, 0, 'white')
        self.SetCellFont(row, 0, wx.Font(8, wx.ROMAN, wx.ITALIC, wx.NORMAL))
        honor = "University of Detroit Chemistry Department"
        self.SetCellValue(row, 0, honor)


# build the data_list, raw_data string is from a …
sneekula 969 Nearly a Posting Maven

Speaking of taxes, check this out.
http://www.ananova.com/news/story/sm_2935937.html

Great idea! Hope the Holy Father (the Pope) is reading this! He sure could use the savings to do good and holy things.

sneekula 969 Nearly a Posting Maven

I am surprised nobody has brought up the old wx.ListBox() widget yet. Well, here it is, a fun thing to experiment with (stole the name_list from vegaseat):

# load, sort and clear a wxPython
# wx.ListBox(parent, id, pos, size, choices, style)

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, name_list):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle)
        self.SetBackgroundColour("green")
        self.name_list = list(name_list)

        self.listbox = wx.ListBox(self, wx.ID_ANY, choices=[])
        self.listbox.Bind(wx.EVT_LISTBOX, self.listboxClick)

        # create action widgets
        self.load_button = wx.Button(self, wx.ID_ANY, "load ListBox")
        self.clear_button = wx.Button(self, wx.ID_ANY, "clear ListBox")
        self.sort_button = wx.Button(self, wx.ID_ANY, "sort ListBox")
        # bind mouse event to an action
        self.load_button.Bind(wx.EVT_BUTTON, self.load_buttonClick)
        self.clear_button.Bind(wx.EVT_BUTTON, self.clear_buttonClick)
        self.sort_button.Bind(wx.EVT_BUTTON, self.sort_buttonClick)
        # create an output widget
        self.label = wx.StaticText(self, wx.ID_ANY, "")

        sizer = wx.GridBagSizer(vgap=5, hgap=5)
        # pos=(row, column)  span=(rowspan, columnspan)
        # wx.ALL puts the specified border on all sides
        sizer.Add(self.load_button, pos=(0, 0), flag=wx.ALL, border=5)
        # listbox spans 6 rows and 2 columns
        sizer.Add(self.listbox, pos=(1, 0), span=(6, 2),
            flag=wx.ALL|wx.EXPAND, border=5)
        sizer.Add(self.clear_button, pos=(7, 1), flag=wx.ALL, border=5)
        sizer.Add(self.sort_button, pos=(7, 0), flag=wx.ALL, border=5)
        sizer.Add(self.label, pos=(8, 0), flag=wx.ALL, border=5)
        self.SetSizer(sizer)

        # size the frame so all the widgets fit
        self.Fit()

    def load_buttonClick(self, event):
        """load the name list into the bistbox"""
        # use self.listbox.Set(name_list) or ...
        for name in self.name_list:
            self.listbox.Append(name)

    def clear_buttonClick(self, event):
        """clear all items from the listbox"""
        self.listbox.Clear()
        self.label.SetLabel("")

    def sort_buttonClick(self, event):
        """sort the items in the listbox"""
        # GetItems() is new in wxPython2.8
        # puts the listbox items into a list
        name_list = self.listbox.GetItems()
        name_list.sort()
        # Set() clears and reloads the listbox
        self.listbox.Set(name_list)

    def listboxClick(self, event):
        """display the selected ListBox item"""
        selected_item …
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

I hope you understand this better:

def main():
    a = 1
    b = 2
    c = 3
    # local variable dictionary
    main_var = vars()
    print main_var  # {'a': 1, 'c': 3, 'b': 2}

    # get the key (variable name) of a certain value, for instance 3
    mvar = [key for key, val in main_var.items() if val==3][0]
    print mvar  # c

    # in somewhat longer form ...
    mvar_list = []
    # extract the key:value pairs from the dictionary
    for key, val in main_var.items():
        # if value is 3 save the key in a list
        if val == 3:
            mvar_list.append(key)
    print mvar_list     # ['c']
    # pick the first item on the list
    print mvar_list[0]  # c

main()
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

You can create a relatively safe numeric input with a function:

def get_num(prompt="Enter a number: "):
    """
    the function will loop until a number has been entered,
    accepts int or float, returns a float
    """
    while True:
        try:
            return float(raw_input(prompt))
        except ValueError:
            print "Numeric value required!"

print get_num()
print get_num("Enter the price: ")
sneekula 969 Nearly a Posting Maven

Local variables are kept in the function's local dictionary which you can access with vars(). To access one function's local dictionary in another function, you have to pass it along:

def my_func(aaa, main_var):
    mvar = [key for key, val in main_var.items() if val==aaa][0]
    print aaa, main_var, mvar  # 123 {'test_var': 123} test_var

def main():
    test_var = 123
    my_func(test_var, vars())

main()
sneekula 969 Nearly a Posting Maven

Will something like this do?

import Tkinter as tk

def set_text_newline(s):
    """start text s on a new line"""
    text1.insert(tk.INSERT, '\n' + s)

root = tk.Tk()
# width=width characters, height=lines of text
text1 = tk.Text(root, width=50, height=12, bg='yellow')
text1.pack()

set_text_newline("line one")
set_text_newline("line two")
set_text_newline("line three")

root.mainloop()
sneekula 969 Nearly a Posting Maven

Something like this could do it:

mystr = 'Hello everybody. Some times THERE ARE upper case words'
mylist = mystr.split()
#print mylist

newstr = ''
for word in mylist:
    if word[0].isupper():
        word = word.capitalize()
    newstr += word + ' '

print newstr

"""
my output -->
Hello everybody. Some times There Are upper case words
"""
sneekula 969 Nearly a Posting Maven

When you make matriz global to the class it just keeps appending to it. Change your code this way:

# Square matrix

import random

class Matriz:
	"""Math operations with matrixes"""

	#matriz = []  # don't make this global!!!!
	grau_matriz = 0;

	def __init__ (self, grau_matriz, inicio):

		self.grau_matriz = grau_matriz

		#Decides if array will be populated with 0's or random numbers
		if inicio == 0:
			self.zero()
		elif inicio == 1:
			self.aleatoria()

	def zero(self):
		"""This method generates a N X N array with zeroes"""
		self.matriz = []
		for i in range(self.grau_matriz):
			linha = []
			for j in range(self.grau_matriz):
				linha.append(0)

			self.matriz.append(linha)

	def aleatoria(self):
		"""This method generates a N X N array with random values"""
		self.matriz = []
		for i in range(self.grau_matriz):
			linha = []
			for j in range(self.grau_matriz):
				linha.append(random.randrange( 1, 10 ))

			self.matriz.append(linha)

	def show(self):

		"""This method prints the array as an N x N format"""

		for i in range(self.grau_matriz):
			for j in range(self.grau_matriz):
				print "%2d " % self.matriz[i][j],
			print

		print


# test it ...
if __name__ == '__main__':
    matrix_a = Matriz(3,1)
    matrix_b = Matriz(3,0)
    matrix_c = Matriz(3,1)

    matrix_a.show()
    print
    matrix_b.show()
    print
    matrix_c.show()
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()
sneekula 969 Nearly a Posting Maven

In this case you are better off to use just Python. Actually, regular expressions aren't necessarily faster. I added plenty of comments to help you:

ts = 'xyz abc mno def'
# separate at space to create a list
space = ' '
qs = ts.split(space)

# search for these items
search_list = ['abc', 'def', 'ghi']

# append this string to search item
s = 'zzz'

# now create a new list with processed search items
new_list = []
for q in qs:
    if q in search_list:
        # concatinate strings
        q += s
    new_list.append(q)

# join the list to form the modified string
new_ts = space.join(new_list)

print new_ts  # xyz abczzz mno defzzz
sneekula 969 Nearly a Posting Maven

Use wx.DisplaySize(), it gives width, height tuple of the display screen

sneekula 969 Nearly a Posting Maven

The latest news release mentions Mexico and South and Central Florida as the source of the Salmonella Saintpaul tainted tomatoes. These areas are also the main producers of tomatoes this time of the season. The bacteria could come from insect or bird feces.

The problem with tomatoes is that Salmonella actually penetrates the skin and can't be washed off. So if you eat a raw tomato, you can get the intestinal revenge!

I doubt that the Iranians did it.

sneekula 969 Nearly a Posting Maven

err why dont you use just use a bit of simple logic and search it on google??if you dont believe me theres nothing i can do...its just your stupidity

Google is just a search engine, it does not verify its collection of data. So there is a huge amount of hogwash you can find there.

Salem commented: "It didn't work, I can't believe it didn't work! I found it on the Internet!" - Adam Savage, Mythbuster +17
sneekula 969 Nearly a Posting Maven

There is a little IDE called PyPE that allows you to run selected code in the shell. It has its own more advanced shell window.

sneekula 969 Nearly a Posting Maven

Sure thing! Glad you liked it.

I'll clean it up tomorrow (or soonish) as there are a few errors and typos, as well as elaborate on some points (such as using multiple horizontal box sizers for more complex widget positioning). I'm also teaching myself about some other widgets, so I'll add them if I feel they could do with explaining.

The best way to learn is to teach a subject. I have enjoyed your presentation of wxPython too.

Compared to Tkinter, wxPython's power is in its clever widgets, a more pythonic approach.

sneekula 969 Nearly a Posting Maven

The Python function eval() will take a string and try to evaluate/interpret it.

BTW, the PyScripter IDE allows you to interpret your source code without having to create an official file. I hate the Python shell, it's okay for one liners only!

If I were stranded on an island and were only allowed one Python GU toolkit, I would take wxPython. Actually, Fuse left a real nice introduction to wxPython programming here:
http://www.daniweb.com/forums/post621707-8.html

sneekula 969 Nearly a Posting Maven

Here is a wxPython tutorial that I have used:
http://wiki.wxpython.org/index.cgi/AnotherTutorial

sneekula 969 Nearly a Posting Maven

It is possible that the smallest forms of life like a virus or even sublife like a misfolded protein or prion (Mad Cow) will do away with larger life forms eventually. Call it God's will.

sneekula 969 Nearly a Posting Maven

It would be nice to have an actual example of the HTML source code or at least the web site's URL. As Jeff said, the BeautifulSoup module (an HTML scraper) is great, but a has a steep learning curve. An interesting project, so let us know any progress.

sneekula 969 Nearly a Posting Maven

2012 may not be the end of the world, but has been mentioned as the year when demand for oil will exceed possible new exploration for oil resources. A situation oil folks call the "Peak Oil".

sneekula 969 Nearly a Posting Maven

If you are using Windows you can do this:

# get the character of a key pressed (no return key needed)
# works only in the command window and with Windows OS
from msvcrt import getch

print "press a char key (escape key to exit)"

while True:
    z = getch()
    # escape key to exit
    if ord(z) == 27:
        break
    print z,

There is also a way to do it with Tkinter running in the background.

sneekula 969 Nearly a Posting Maven

Your initial problems stem from the fact that you are mixing tabs and spaces in your indentations. It really loused up the code on my editor. Stick with spaces (4) only!

Also, when you click the stop button during sleep(1), it most likely will not respond. You may need to use Tkinter's after().

sneekula 969 Nearly a Posting Maven

Actually the way I heard it was more like this - Why do married men die younger? They want to!

(And before anyone complains, yes, I am married, and no, I don't feel that way personally).

KDoiron, welcome to DaniWeb! I remember it was you that introduced me to Cole's Law.

sneekula 969 Nearly a Posting Maven

If you were a file I'd hit delete.

Very nice quotation indeed!

For the folks who believe that there is no God, please tolerate those of us that need God in our life. A simple request.

sneekula 969 Nearly a Posting Maven

You are commiting one of the cardinal violations in Python when you mix tabs and spaces in your indentations. Many editors do not match the correct amount of spaces with your tabs, now you have a mess on your hand. Please use the customary 4 spaces only, avoid tabs!

sneekula 969 Nearly a Posting Maven

Come on, AD - give it up! We want a hint - I think the standard is book - chapter - line(s) (zeke 12: 13-69).

Apocalypse 16:13-16
13 And I saw from the mouth of the dragon, and from the mouth of the beast, and from the mouth of the false prophet, three unclean spirits like frogs.
14 For they are the spirits of devils working signs, and they go forth unto the kings of the whole earth, to gather them to battle against the great day of the Almighty God.
15 Behold, I come as a thief. Blessed is he that watcheth, and keepeth his garments, lest he walk naked, and they see his shame.
16 And he shall gather them together into a place, which in Hebrew is called Armagedon.

Educate yourself further at:
http://www.theworkofgod.org/armagedn.htm

If in doubt, contact former President of the US Jimmy Carter.

sneekula 969 Nearly a Posting Maven

that always happens in history. Crusades anyone?

Crusades have come and gone, except maybe the Iraq war will last another 95 years, but with the introduction of more and more powerful weaponry, there could very well be a final crusade in our life time.

As you most likely know, the reborn Christians belief in a gigantic bloodbath in the Middle East with everybody but themselves going to hell. It's in the Bible! Any questions, ask Jimmy Carter.

sneekula 969 Nearly a Posting Maven

I believe that the end of the world will come when people believing in different beliefs start to kill each other on a massive scale.

Something like my God is better than your God. Most likely, my God told me to kill all nonbelievers with this divine arsenal of nuclear weapons.

Salem commented: Yes, the well armed zealot is always a problem +16
sneekula 969 Nearly a Posting Maven

I just read the this year the Arctic will be ice free in the summer for the first time in 50 million years.

sneekula 969 Nearly a Posting Maven

While men die doing stupid things to satisfy the demands of their spouces, our nursing homes are filling up with feeble old biddies, barely a man in sight. Yes, women live longer than men.

sneekula 969 Nearly a Posting Maven

I assume that livewires is just a wrapper for Python and Tkinter using a different syntax. The syntax might be easier to understand for youngsters, but simply adds another layer of potential errors. I don't think very many folks use this module. I am not even sure where to get it?

For instance, does read_number() read an integer or a float, or does it use eval() for both?

sneekula 969 Nearly a Posting Maven

Nice solution Mitko, can even be made mildly simpler:

listsorted = sorted(listunsorted, key=lambda x: x[0])
sneekula 969 Nearly a Posting Maven

In your case I would worry a lot. If your wife gets interested in computer programming, she could turn into a 'computer nun' and totally neglect you!

BTW, your wife wouldn't be a chain saw enthusiast, would she?