Ene Uran 638 Posting Virtuoso

Hint:
Looks to me like you are creating the same label over and over again.

Ene Uran 638 Posting Virtuoso

I don't think getting the values will be a problem, because I've heard of GetValues() and Google it for help.

The problem is: the self.panel doesn't at all work...

One more question:

viewm=wx.Menu()
viewm.Append(202,"About")        self.Bind(wx.EVT_MENU,self.About,id=302)

def About(self,event,id=302):
    about=wx.AboutDialogInfo()

-but it doesn't work. How do I specify the ID when defining the function?

Thanks

You don't need the id as a method parameter, but at least try to match the id in the lines above, 202 is not the same as 302.

self.panel will work if you use it throughout the class! Search for 'panel' with your editor.

Ene Uran 638 Posting Virtuoso

In this case you have to set a flag like this:

import sys

# there is a commandline
if len(sys.argv) > 1:
    mylist = []
    # sys.argv[0] is the program filename, slice it off
    flag = False
    for element in sys.argv[1:]:
        if element == '-f':
            flag = False
        if flag == True:
            mylist.append(element)
        if element == '-n':
            flag = True


else:
    print "usage %s element1 element2 [element3 ...]" % sys.argv[0]
    sys.exit(1)

# if the arguments were -n 1 2 3 4 -f abc.txt
# mylist should be  ['1', '2', '3', '4']
print(mylist)
Ene Uran 638 Posting Virtuoso

Give this a try:

import sys

# there is a commandline
if len(sys.argv) > 1:
    mylist = []
    # sys.argv[0] is the program filename, slice it off
    for element in sys.argv[1:]:
        mylist.append(element)
else:
    print "usage %s element1 element2 [element3 ...]" % sys.argv[0]
    sys.exit(1)

# if the arguments were 1 2 3 4 5
# mylist should be ['1', '2', '3', '4', '5']
print(mylist)
Ene Uran 638 Posting Virtuoso

You can trap error details this way:

import datetime as dt

def ObtainDate():
    isValid=False
    while not isValid:
        userIn = raw_input("Type Date dd/mm/yy: ")
        try: # strptime throws an exception if the input doesn't match the pattern
            d1 = dt.datetime.strptime(userIn, "%d/%m/%y")
            isValid=True
#Perhaps set another try here.
            print d1, type(d1)  # 2003-07-15 00:00:00 <type 'datetime.datetime'>
            "convert datetime object to a 10 character string"
            d2 = str(d1)[:10]
            print d2, type(d2)  # 2003-07-15 <type 'str'>
        except ValueError, what_error:
            print what_error
            print "Try again! dd/mm/yy\n"
    Fname = "data.dat"
    newFname = d2 + Fname
    return newFname

print ObtainDate()  # 2003-07-15data.dat
Ene Uran 638 Posting Virtuoso

Ouch! Thanks Lingson, I overlooked that range() does not return a list in Python3. So I give you the correct version here:

# exploring multiple Tkinter check buttons
# check buttons allow more than one item to be selected/checked
# ene

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

def cb_checked():
    # show checked check button item(s)
    label['text'] = ''
    for ix, item in enumerate(cb):
        if cb_v[ix].get():
            label['text'] += '%s is checked' % item['text'] + '\n'


root = tk.Tk()

mylist = [
'apple',
'orange',
'banana',
'pear',
'apricot'
]

# list(range()) needed for Python3
cb = list(range(len(mylist)))
cb_v = list(range(len(mylist)))
for ix, text in enumerate(mylist):
    # IntVar() tracks checkbox status (1=checked, 0=unchecked)
    cb_v[ix] = tk.IntVar()
    # command is optional and responds to any cb changes
    cb[ix] = tk.Checkbutton(root, text=text,
        variable=cb_v[ix], command=cb_checked)
    cb[ix].grid(row=ix, column=0, sticky='w')

label = tk.Label(root, width=20)
label.grid(row=ix+1, column=0, sticky='w')

# you can preset check buttons (1=checked, 0=unchecked)
cb_v[3].set(1)
# show initial selection
cb_checked()

root.mainloop()

Now it works with Python2 and Python3 as planned. I downloaded the Editra IDE, now I can easily check my code in both Python versions.

I will contact vegaseat to correct the sample code, since the error appears in both samples.

Ene Uran 638 Posting Virtuoso

A nice brain teaser to get to know Python, here are some hints:

"""wants dictionary object -->
{'toy301': ('Flying Kite', [('AB339',2),('DC302',2),('FR377',2),
('JK301),1),('YU301',1),('EE301',1),('FW301),1)])}
"""

# typical data line from a file
line = """\
toy301, Flying Kite, AB339:2,DC302:2,FR377:2,JK301:1,YU301:1,EE301:1,FW301:1
"""

# first split the line at the commas
list1 = line.split(",")
print(list1)

"""result -->
['toy301', ' Flying Kite', ' AB339:2', 'DC302:2', 'FR377:2',
'JK301:1', 'YU301:1', 'EE301:1', 'FW301:1\n']
"""

# next create a list of tuples from items that have ':'
tuple_list = []
for item in list1:
    # strip off trailing newline
    line = line.rstrip()
    if ':' in item:
        text, num = item.split(":")
        tuple_list.append((text, int(num)))

print(tuple_list)

"""result -->
[(' AB339', 2), ('DC302', 2), ('FR377', 2), ('JK301', 1),
('YU301', 1), ('EE301', 1), ('FW301', 1)]
"""

# now you are ready to piece together the dictionary object from
# parts in list1 and the tuple_list
Ene Uran 638 Posting Virtuoso

There is a working example of Tkinter's radio buttons and also a comparative look at check buttons at:
http://www.daniweb.com/forums/showpost.php?p=966368&postcount=58

Ene Uran 638 Posting Virtuoso

OOOOOH, putpixel places an image? Or does it draw a dot?

I guess it's time to experiment...

An image is made up of dots.

Ene Uran 638 Posting Virtuoso

If you are specifically looking for the text line:
'you love me'
then sravan953 code works best.

leegeorg07 code using 'in' would also give you a positive with a line like:
'you love me not'
which may be misleading.

Ene Uran 638 Posting Virtuoso

At this point you have to show us your code, so we can see how you configured the sizer.

Ene Uran 638 Posting Virtuoso

Put the ListBox in a sizer.

Ene Uran 638 Posting Virtuoso

Simply use list():

list1 = ['a', 'b', 'c', 'd']
# this will create a new list with a different mem ref
temp_list1 = list(list1)
for i in range(len(list1)):
    temp_list1[i] = "1"
print list1;              # ['a', 'b', 'c', 'd']
print temp_list1;         # ['1', '1', '1', '1']

For nested lists you need to use deepcopy() from module copy.

shadwickman commented: Well I learned something new about using list() :P +4
Ene Uran 638 Posting Virtuoso

Might as well go with:

...
background = "C:\\python26\\stuff\\bg.jpg"
background_surface = pygame.image.load(background)
...

Since that kind of directory name is meant for Windows only.

Ene Uran 638 Posting Virtuoso

Where are your FileIn and FileOut strings?

Ene Uran 638 Posting Virtuoso

You mean something like this:

# data string read from a file
data = """\
gnl|dbSNP|rs13484118 gi|62750812|ref|NC_005111.2|NC_005111 95 20 1 0 68 87 31017559 31017578 4.4 32.3
gnl|dbSNP|rs13484118 gi|62750812|ref|NC_005111.2|NC_005111 91.67 24 2 0 63 86 35247737 35247714 4.4 32.3
gnl|dbSNP|rs13484118 gi|62750812|ref|NC_005111.2|NC_005111 91.67 24 2 0 64 87 40549054 40549031 4.4 32.3
gnl|dbSNP|rs13484118 gi|62750812|ref|NC_005111.2|NC_005111 92 24 2 0 63 86 42462636 42462659 4.4 32.3
gnl|dbSNP|rs13484118 gi|62750812|ref|NC_005111.2|NC_005111 95 20 1 0 63 82 45774066 45774085 4.4 32.3
"""

new_data = ""
for line in data.split('\n'):
    # replace each space with a tab
    line = line.replace(" ", "\t")
    new_data += line + '\n'

# test only ...
print(new_data)

# now write new_data string to a file
lllllIllIlllI commented: ahh! Beat me too it :P +4
Ene Uran 638 Posting Virtuoso

Let's see if the Omron Smile Scan system works on holders of State of California short term debts and bonds. California has started pay off with I.O.U.'s rather than actual money.

jephthah commented: ouch :( +12
Ene Uran 638 Posting Virtuoso

One way to do this is to pad each word with spaces at the end to make the words equal in length (max length + 2):

s = """\
dasj    dhsahdwe	dhasdhajks	ewqhehwq	dsajkdhas
edward das	dsaw	das	daswf
fjdk    ewf	jken	dsajkw	dskdw
hklt    ewq	vn1	daskcn	daskw
"""

# create a word list
mylist = s.split()
#print mylist

# find maximum word length
length = 0
for w in mylist:
    size = len(w)
    if size > length:
        length = size

#print length

# pad spaces to the end of each word
# add a newline to every fifth word
newlist = []
# max length + 2 spaces
pad = length + 2
ix = 1
for w in mylist:
    size = len(w)
    # pad with spaces
    w = w + ' '*(pad - size)
    if ix % 5 == 0:
        # add a newline
        w = w + '\n'
    newlist.append(w)
    ix += 1

#print newlist

# now show the words in the new list
for w in newlist:
    print w,

"""
my display -->
dasj         dhsahdwe     dhasdhajks   ewqhehwq     dsajkdhas
edward       das          dsaw         das          daswf
fjdk         ewf          jken         dsajkw       dskdw
hklt         ewq          vn1          daskcn       daskw
"""

I used space padding, because tabs are set differently depending on the editor you want to display with.

Ene Uran 638 Posting Virtuoso

What do you expect to happen with your test code?
If you test the module properly, it will work:

# create two separate windows with a button on it
# notice that the close button will close both windows

from PyQt4 import QtGui, QtCore

class QuitButtonAA(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.setGeometry(100, 200, 250, 150)
        self.setWindowTitle('Icon AA')

        quit = QtGui.QPushButton('Close', self)
        quit.setGeometry(10, 10, 60, 35)

        self.connect(quit, QtCore.SIGNAL('clicked()'),
            QtGui.qApp, QtCore.SLOT('quit()'))

class QuitButtonBB(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Icon BB')

        quit = QtGui.QPushButton('Close', self)
        quit.setGeometry(10, 10, 60, 35)

        self.connect(quit, QtCore.SIGNAL('clicked()'),
            QtGui.qApp, QtCore.SLOT('quit()'))


# test the potential module
if __name__ == '__main__':
    import sys
    app =  QtGui.QApplication(sys.argv)
    b1 = QuitButtonAA()
    b1.show()
    b2 = QuitButtonBB()
    b2.show()
    app.exec_()
Ene Uran 638 Posting Virtuoso

Take the spaces out of ""[code = python]"

Ene Uran 638 Posting Virtuoso

@sravan953
also remember that in Python2 ' /' is an integer division by default.
For instance 12/15 gives you a zero. This has changed in Python3.

Ene Uran 638 Posting Virtuoso

Your problem is too simple to bother with regex:

mylist = ['adam', 'bill', 'jon/juan']

newlist = [item.replace('/', '') for item in mylist]

print(mylist)   # ['adam', 'bill', 'jon/juan']
print(newlist)  # ['adam', 'bill', 'jonjuan']
Ene Uran 638 Posting Virtuoso

I you are on Windows and have several versions of Python installed, you can write a little batch file to make sure the IDLE of the correct version is runnig:

REM a batch file to force IDLE to use Pyhon30
REM saved as IDLE30.bat
C:\Python30\pythonw.exe -u C:\Python30\Lib\idlelib\idle.pyw

The poor quality keyboard on my HP notbook coputer is givig me the fits!

Ene Uran 638 Posting Virtuoso

Maybe something like this:

import random

low = 1
high = 9

mylist = [(random.randint(low, high), ) for k in range(10)]

print(mylist)

"""
a possible display of one element tuples -->
[(9,), (5,), (6,), (2,), (8,), (3,), (4,), (2,), (6,), (1,)]
"""
Ene Uran 638 Posting Virtuoso
Ene Uran 638 Posting Virtuoso

I think we may have talked about this before, but I can't find it. Here is a way to use a sound file inside the Python code and play it. First create a base64 encoded string of the binary sound file:

# create a base64 encoded string from binary sound data
# and limit the length of each data line to n characters
# ene

import base64

def text_lines(data, n):
    """
    write a long one line text as lines of n char each
    """
    s = ""
    for ix, c in enumerate(data):
        if ix % n == 0 and ix != 0:
            s += c + '\n'
        else:
            s += c
    return s

# pick a wave file that is in the working folder
wave_file = "pop.wav"
# this is a binary read
data = base64.b64encode(open(wave_file, 'rb').read())
data = text_lines(data, 70)
print "wav_base64='''\\\n" + data + "'''"

"""
highlight and copy the resulting base64 wav string to embed in program
code, use wav = base64.b64decode(wav_base64) to decode to binary data:

wav_base64='''\
UklGRuABAABXQVZFZm10IBAAAAABAAEAESsAABErAAABAAgAZGF0YbsBAACAgICAgICAgIC
AgICAfX12aVtQS0hJSk5TZpWyv8LBwMC/vry2nWxLPTs9PT5AR05pn77BwcC/vruxlGtJP
T09PkBHU3qrv8DAv7+7tKiGWUA8PT4+Qk1tm7fAv7++ubKmhl1CPD0+P0NPbZayv8C/vbe
vooNdRD0+PkBIWXWVrru/vbmypo5uU0I+P0NLWG6JorO7vLm0rJyBZlBEQkNIUF5xiJ2wu
bq4s6qZg21ZTUhITFRhcoaaqLGzsayilIFvYFVQUFNZY29/j52orKunnpKFdmheWFVWWmF
seYiXoqmrqaKXi390amRfXmBka3aDj5ifoqGemZGIfXJpY2FiZmx0fYePlpqcmpSNhHpyb
Wloam91foaNk5eXlZGMhH12b2xqam1xd32Ei5CVlpSPiYF6dHFvbnByd36Fi4+SkY6KhoN
+end3d3h8gYaKjIyMioeDf3t4dnZ3eX2BhYiKi4uJhoJ+eXZ1dnd6fICFiY2PjoyHgnx3d
XNzdHZ6f4WKjpCPjIiEf3t3dHNzdXh8goeLjY2NiYWBfHh0cnJzdnl9gYSGh4aFg398eXd
2d3l8foCChIaIh4aEgQA='''

"""

Now you can transfer the result to your Python program and play the sound without having to attach the sound file:

# playing a base64 encoded wave sound string with wxPython's
# wx.SoundFromData(sound_data) and sound.Play()
# ene

import wx
import base64

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize, sound_data):
        wx.Frame.__init__(self, parent, -1, mytitle, size=mysize)
        self.SetBackgroundColour("blue")
        # use a small delay to display the frame before sound …
Nick Evan commented: Random rep for effort put in 'beginner' threads :) +18
sneekula commented: wonderful +8
Ene Uran 638 Posting Virtuoso

Python 2.5.4 is the version I have installed. Python 2.6 has all sorts of problems at least on Windows, since it is compiled with a different MS C compiler. A good number of modules are simply not available for Python 2.6. Python 2.6 is supposed to help you to transition better to the new Python3. I think that is questionable.

Ene Uran 638 Posting Virtuoso

In order to make buttons behave like standard buttons in your dialog box, you simply create an image button from a standard button and an image:

class BitmapDialog(wx.Dialog):
    def __init__(self, text):
        wx.Dialog.__init__(self, None, -1, title="BitmapDialog", 
            size=(250,150))
        
        bmp = wx.Bitmap('ok.png')
        w, h = bmp.GetSize()
        x = 35
        y = 90
        wx.StaticBitmap(self, -1, bmp,
            pos=(x, y))
        okButton = wx.Button(self, wx.ID_OK, ' OK ', 
            pos=(x+w, y), size=(w*2, h))
        okButton.SetDefault()

        bmp = wx.Bitmap('cancel.png')
        w, h = bmp.GetSize()
        x = 135
        y = 90
        wx.StaticBitmap(self, -1, bmp,
            pos=(x, y))
        cancelButton = wx.Button(self, wx.ID_CANCEL, ' Cancel ', 
            pos=(x+w, y), size=(w*2, h))

Actually, the way these buttons respond to keystrokes depends on the OS.

Ene Uran 638 Posting Virtuoso

Just to add to shibby's very nice explanation:

# passing a class variable to other classes

class C1(object):
    def __init__(self):
        print("in class C1")
        # self makes mc1 available to the class instance
        self.mc1 = 77

class C2(object):
    mc2 = 88
    def __init__(self):
        print("in class C2")
        # create an instance of C1 within C2 (shibby's example)
        ac1 = C1()
        # now access mc1 using this instance
        print(ac1.mc1)  # 77
        # show C2's own variable
        print(self.mc2)  # 88
        
class C3(C1):
    """C3 inherits C1"""
    mc3 = 99
    def __init__(self):
        print("in class C3")
        # make C1 part of C3's self
        C1.__init__(self)
        print(self.mc1)  # 77
        # show C3's own variable
        print(self.mc3)  # 99

# create instances of class C2 and class C3
ac2 = C2()
ac3 = C3()

"""
my display -->
in class C2
in class C1
77
88
in class C3
in class C1
77
99
"""
Ene Uran 638 Posting Virtuoso

Did you have a bad day?

Ene Uran 638 Posting Virtuoso

Let's get a little playful and display a text in rainbow colors:

# use wxPython's wx.richtext.RichTextCtrl
# to create rainbow colored text

import wx
import wx.richtext

class MyFrame(wx.Frame):
    def __init__(self, parent, title, rainbow_text):
        wx.Frame.__init__(self, parent, -1, title, size=(560, 220))
        self.SetBackgroundColour("white")
        
        self.rich = wx.richtext.RichTextCtrl(self, -1, value="")
        self.rich.BeginFontSize(40)
        for c, colour in rainbow_text:
            self.rich.BeginTextColour(colour)
            self.rich.WriteText(c)
            self.rich.EndTextColour()


rainbow = ['red', 'coral', 'yellow', 'green', 'blue']

text = """
 Welcome to fabulous
        Las Vegas"""

# create a list of (char, colour) tuples
rainbow_text = []
ix = 0
for c in text:
    if c.isalpha():
        colour = rainbow[ix]
        if ix < len(rainbow)-1:
            ix += 1
        else:
            ix = 0
    else:
        colour = 'white'
    rainbow_text.append((c, colour))

app = wx.App(0)
title = 'Rainbow Text'
MyFrame(None, title, rainbow_text).Show()
app.MainLoop()
Ene Uran 638 Posting Virtuoso

The pygame.KEYDOWN event figures this one out, just put it into an if statement.

Ene Uran 638 Posting Virtuoso

You are making good progress on your own!

Here is a typical example for some widgets you are interested in:

# a wxPython example for label widgets (wx.StaticText) 
# and an entry or edit widget (wx.TextCtrl)

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle):
        # -1 = wx.ID_ANY (wxPython will pick a unique id value)
        wx.Frame.__init__(self, parent, -1, mytitle, 
            pos=(100, 150), size=(300, 150))
        self.SetBackgroundColour("yellow")

        s = "Enter your name below:"
        label = wx.StaticText(self, -1, s)
        self.edit = wx.TextCtrl(self, -1, value="") #, size=(200, 20))
        # respond to enter key when focus is on self.edit
        self.edit.Bind(wx.EVT_TEXT_ENTER, self.onEnter)
        self.result = wx.StaticText(self, -1)

        # position your widgets using a box sizer
        # (line up in a vertical stack)
        # wx.ALL --> widget has specified border on all sides
        # wx.EXPAND --> widget will expand to fit resized frame
        sizer_v = wx.BoxSizer(wx.VERTICAL)
        sizer_v.Add(label, 0, flag=wx.ALL|wx.EXPAND, border=4)
        sizer_v.Add(self.edit, 0, flag=wx.ALL|wx.EXPAND, border=4)
        sizer_v.Add(self.result, 0, flag=wx.ALL|wx.EXPAND, border=8)
        self.SetSizer(sizer_v)
        
        # put the cursor in the edit widget
        self.edit.SetFocus()
        
    def onEnter(self, event):
        """the enter key has been pressed in self.edit"""
        name = self.edit.GetValue()
        s = "You entered the name: " + name
        self.result.SetLabel(s)
        

app = wx.App(0)
MyFrame(None, 'testing wx.TextCtrl').Show()
app.MainLoop()
Ene Uran 638 Posting Virtuoso

Well, wxPython is a very powerful GUI toolkit, well worth learning. It's parent is wxWindows written in C++, this will show up in some of the manuals. A lot of people on this forum use it, so you should get lots of help. Just keep asking questions.

Ene Uran 638 Posting Virtuoso

Here is an example without a titlebar and showing fullscreen:

# wx.Frame with no title bar and showing fullscreen
# modified from vegaseat's example

import wx

def exit(event):
    frame.Close(True)

app = wx.App(0)
# create a window, no-parent, -1 is default ID, style with no titlebar
frame = wx.Frame(parent=None, id=-1, pos=(50,100), size=(300,200), 
    style=wx.MINIMIZE_BOX)
frame.SetBackgroundColour('green')
frame.ShowFullScreen(True, style=wx.FULLSCREEN_ALL)

# provide exit for a frame without titlebar
quit = wx.Button(frame, id=-1, label='Exit', pos=(0, 0))
quit.Bind(wx.EVT_BUTTON, exit)

# show the window
frame.Show(True)

# start the event loop
app.MainLoop()
Ene Uran 638 Posting Virtuoso

Use this to clear the screen on a console program:

import sys
# on Windows
os.system("CLS") 
# on Linux
os.system('clear')

Also for my taste avoid using globals, they can get you into conflicts. You can generally pass them to and from functions in the arguments.

Do you want to use wxPython because you want to learn it? The Tkinter GUI toolkit is somewhat simpler to use, but then getting into GUI programming is somewhat of a steep learning curve anyway.

Ene Uran 638 Posting Virtuoso

Oui, before I forget, take a look at the wx.RichTextCtrl example by Snee in the 'Starting wxPython' thread, that seems to be simpler for your purposes:
http://www.daniweb.com/forums/post763339-103.html

Here is a simple example:

# a simple sign using wx.richtext.RichTextCtrl()

import wx
import wx.richtext as rt

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
        self.SetBackgroundColour("white")
        
        rich = rt.RichTextCtrl(self, wx.ID_ANY, value="")
        # default is black text
        rich.BeginFontSize(26)
        rich.BeginBold()
        rich.WriteText(" You are in ")
        rich.BeginTextColour('red')
        rich.WriteText("danger ")
        rich.EndTextColour()
        rich.WriteText("at that spot!")
        rich.EndBold()
        rich.EndFontSize()
        rich.WriteText("\n\n        The management")
        

app = wx.App()
mytitle = 'A wx.RichTextCtrl Sign'
width = 600
height = 140
# create the MyFrame instance and show the frame
MyFrame(None, mytitle, (width, height)).Show()
app.MainLoop()
Ene Uran 638 Posting Virtuoso

To my knowledge you cannot selectively color text with the simple wx.TextCtrl widget, for that you need the wx.StyledTextCtrl widget.

Ene Uran 638 Posting Virtuoso

My advice, don't use the Python Shell for programming, use an editor. The Python Shell interative interpreter is only for very short tests. It is basically there to confuse beginners and discourage them from using Python. :)

Ene Uran 638 Posting Virtuoso

There are a flock of badly written and rather outdated Python books on the market. I would go for some of the free online books.

Swaroop C.H. has rewritten his excellent beginning Python tutorial for Python30:
http://www.swaroopch.com/notes/Python_en:Table_of_Contents

How to Think Like a Computer Scientist - Learning with Python
written by a college professor, a high school teacher, and a professional programmer:
http://www.thinkpython.com
Foreword by David Beazley, University of Chicago:
http://www.greenteapress.com/thinkpython/html/foreword.html
http://www.ibiblio.org/obp/thinkCSpy/

Above updated: "Think like a Python Programmer" (PDF format):
http://greenteapress.com/thinkpython/thinkPP.pdf

Ene Uran 638 Posting Virtuoso

HTML code is easy to learn and you can format text using a simplified version of it, and show it in the wx.html.HtmlWindow() widget. Here is an example:
http://www.daniweb.com/forums/post803532-107.html

Ene Uran 638 Posting Virtuoso

The wx.html.HtmlWindow widget is also very useful to show text in changing size and colour:

# using wxPython's
# wx.html.HtmlWindow(parent, id, pos, size, style, name)
# to show colourful text using relatively simple html code

import wx
import wx.html

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize, html_code1, html_code2):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle,
            size=mysize)

        # create an html label/window
        htmlwin1 = wx.html.HtmlWindow(self, wx.ID_ANY)
        htmlwin1.SetPage(html_code1)
        
        htmlwin2 = wx.html.HtmlWindow(self, wx.ID_ANY)
        htmlwin2.SetPage(html_code2)
        
        # position the labels with a box sizer
        sizer_v = wx.BoxSizer(wx.VERTICAL)
        sizer_v.Add(htmlwin1, proportion=1, flag=wx.EXPAND)
        sizer_v.Add(htmlwin2, proportion=2, flag=wx.EXPAND)
        self.SetSizer(sizer_v)


# simple HTML code ...
# text between <B> and </B> is bold
# <BR> inserts a line break (or new line)
# text between <FONT color="blue"> and </FONT> is that color
# add size to the FONT tag
html_code1 = """\
This shows you how to display text in color
<BR>
<FONT color="blue">like blue text</FONT>
<FONT color="red"> or red text</FONT>
<B> or maybe just bold ...</B>
<BR><BR>
<FONT color="green" size=5>
You are in extreme
<FONT color="red" size=5>danger</FONT>
standing so close!
</FONT>
"""

# a few more HTML tags ...
# use <BODY> tags to add a background colour
# text between <H3> and </H3> is header size
# etc. etc. just experiment with the <> tags
html_code2 = """\
<BODY bgcolor="#FFE47E">
look at the new background colour ...
<H3>large header size</H3><H2>larger header size</H2>
<BR>
<FONT size="+4">even larger font size</FONT>
<BR><BR>
<FONT color="red" size="+4">larger </FONT>
<FONT color="green" size="+4">size </FONT>
<FONT color="blue" size="+4">and </FONT>
<FONT color="magenta" size="+4">color</FONT>
<BR>
</BODY>
"""

app = wx.App()
mytitle …
Ene Uran 638 Posting Virtuoso

Just a WAG, but it looks like you changed your OS permission/access level.

Ene Uran 638 Posting Virtuoso

Oh yes, Python has an array type, but you must import module array:

# module array has Python's array type

import array

# Python25 use 'c' as the character typecode
# Python30 uses unicode character typecode 'u'
char_array = array.array('c', 'hello world')

print(char_array[0])    # h
print(char_array)       # array('c', 'hello world')

# 'i' uses a signed integer of 2 bytes
int_array = array.array('i', [2, 4, -11])

print(int_array[2])     # -11
print(int_array)        # array('i', [2, 4, -11])

# 'f' uses 4 bytes and 'd' uses 8 bytes per element 
float_array = array.array('d', [1.0, 2.0, 3.14])

print(float_array[2])  # 3.14

for n in float_array:
    print(n)


# get more information on module array
help('array')

Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time. Arrays use up less space in memory, for a limited number of applications this is important.

scru commented: You knowledge of Python is astounding +5
Ene Uran 638 Posting Virtuoso

Just an observation, I would avoid using variable names like l1, l2 and so on, they look a lot like numbers 11, 12.

Here is an example how to use Python function map():

q = [1, 2, 3, 4, 5]

# map applies float() to every element in the list q
qf = map(float, q)

print(qf)  # [1.0, 2.0, 3.0, 4.0, 5.0]
Ene Uran 638 Posting Virtuoso

The str() function returns a normal string. Test it out:

s = u"a unicode string"

d = {}
d['a'] = s

print(d)  # {'a': u'a unicode string'}

d['b'] = str(s)  # str() converts s to a normal string

print(d)  # {'a': u'a unicode string', 'b': 'a unicode string'}
Ene Uran 638 Posting Virtuoso

First of all, do yourself and the rest of us a big favor and do not use tabs for indentations. As you can see, your code shows up badly in the Daniweb code area. Most of us use 4 spaces for indentation.

Here is an example of wxPython's GridSizer to display BitmapButtons in a nice grid. The bitmap images in this case are provided by wxPython's ArtProvider:

# exploring wxPython's GridSizer, ArtProvider and BitmapButton

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, art_list):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle,
            size=(360, 255))
        self.SetBackgroundColour('green')
        
        self.art_list = art_list
        
        # main sizer forms a border
        vsizer = wx.BoxSizer(wx.VERTICAL)
        
        # wx.GridSizer(rows, cols, vgap, hgap)
        # art_list has 48 items so make it 6x8
        gsizer = wx.GridSizer(6, 8, 5, 5)

        self.btn = range(len(self.art_list))
        # fill the drid sizer using a loop
        for ix, art in enumerate(self.art_list):
            # set up a consecutive unique id for each button
            id = 1000 + ix
            bmp = wx.ArtProvider.GetBitmap(art, wx.ART_OTHER, (16, 16))
            self.btn[ix] = wx.BitmapButton(self, id, bitmap=bmp)
            # the gridsizer fills left to right one row at a time
            gsizer.Add(self.btn[ix], 0, wx.ALL|wx.EXPAND, border=2)
            self.btn[ix].Bind(wx.EVT_BUTTON, self.btnClick)

        # add to the main sizer and set
        vsizer.Add(gsizer, 0, wx.EXPAND|wx.ALL, border=10)
        self.SetSizer(vsizer)

    def btnClick(self, event):
        """do something"""
        # get the art_id of the button clicked from the art_list
        art_id = self.art_list[event.GetId() - 1000]
        # show the art_id in the frame title bar
        self.SetTitle(str(art_id))


# constants of art items in ArtProvider 
art_list = [
wx.ART_ADD_BOOKMARK, 
wx.ART_DEL_BOOKMARK, 
wx.ART_HELP_SIDE_PANEL,
wx.ART_HELP_SETTINGS, 
wx.ART_HELP_BOOK, 
wx.ART_HELP_FOLDER,
wx.ART_HELP_PAGE, 
wx.ART_GO_BACK, 
wx.ART_GO_FORWARD,
wx.ART_GO_UP,
wx.ART_GO_DOWN,
wx.ART_GO_TO_PARENT, …
Ene Uran 638 Posting Virtuoso

As long as there is no comma in your individual data elements, you can use function join() and replace() in this manner:

q = ['23', 'CL', '006', '2004', 'DBA8ORPU', '41', '8Y', '0', 'S0111P', '2']

s = ",".join(q).replace(",", " ")

print(s)

"""
my result -->
23 CL 006 2004 DBA8ORPU 41 8Y 0 S0111P 2
"""
Ene Uran 638 Posting Virtuoso

As girls get smarter, they are almost impossible to put up with.

Ene Uran 638 Posting Virtuoso

The 'u' implies the use of unicode (a more international character set).