Ene Uran 638 Posting Virtuoso

Okay, here is a simple create a window, input through an Entry, action with a Button and output to a Label code example:

# a simple Tkinter number guessing game
# shows how to create a window, an entry, a label, a button,
# a button mouse click response, and how to use a grid for layout

from Tkinter import *
import random

def click():
    """the mouse click command response"""
    global rn
    # get the number from the entry area
    num = int(enter1.get())
    # check it out
    if num > rn:
        label2['text'] = str(num) + " guessed too high!"
    elif num < rn:
        label2['text'] = str(num) + " guessed too low!"
    else:
        s1 = str(num) + " guessed correctly!"
        s2 = "\n Let's start a new game!"
        label2['text'] = s1 + s2
        # pick a new random number
        rn = random.randrange(1, 11)
    enter1.delete(0, 2)


# create the window and give it a title
root = Tk()
root.title("Heidi's Guess A Number Game")

# pick a random integer from 1 to 10
rn = random.randrange(1, 11)

# let the user know what is going on
label1 = Label(root, text="Guess a number between 1 and 10 -->")
# layout this label in the specified row and column of the grid
# also pad with spaces along the x and y direction
label1.grid(row=1, column=1, padx=10, pady=10)

# this your input area
enter1 = Entry(root, width=5, bg='yellow')
enter1.grid(row=1, column=2, padx=10)
# put the cursor into the entry field
enter1.focus()

# this is your mouse …
Ene Uran 638 Posting Virtuoso

This is one way to produce a syntax error:
pint " Hello Cu Python!"
or ...
Print " Hello Cu Python!"

Remember Python is case sensitive.

Ene Uran 638 Posting Virtuoso

MikeyFTW,
looks like you have to study up on Tkinter GUI programming.

Here is an introduction:
http://www.pythonware.com/library/tkinter/introduction/index.htm

In simple terms, create a frame/window/root, input through an Entry, action with a Button and output to a Label.

Ene Uran 638 Posting Virtuoso

riyadhmehmood, do not hijack somebody elses thread! Very bad manners. Start your own thread.

Ene Uran 638 Posting Virtuoso

Here is an example of using the Tkinter GUI toolkit to bring up a 5 second splash screen. All the info you want needs to be written into the picture itself, using one of the popular image editing utilities:

# create a splash screen, 80% of display screen size, centered,
# displaying a GIF image with needed info, disappearing after 5 seconds

import Tkinter as tk

root = tk.Tk()
# show no frame
root.overrideredirect(True)
width = root.winfo_screenwidth()
height = root.winfo_screenheight()
root.geometry('%dx%d+%d+%d' % (width*0.8, height*0.8, width*0.1, height*0.1))

# take a .jpg picture you like, add text with a program like PhotoFiltre
# (free from http://www.photofiltre.com) and save as a .gif image file
image_file = "LakeSplash.gif"
#assert os.path.exists(image_file)
# use Tkinter's PhotoImage for .gif files
image = tk.PhotoImage(file=image_file)
canvas = tk.Canvas(root, height=height*0.8, width=width*0.8, bg="brown")
canvas.create_image(width*0.8/2, height*0.8/2, image=image)
canvas.pack()

# show the splash screen for 5000 milliseconds then destroy
root.after(5000, root.destroy)
root.mainloop()

# your console program can start here ...
print "How did you like my informative splash screen?"
Ene Uran 638 Posting Virtuoso

Something like this should do:

s = 'xxxxx - xxxxx'
space = ' '
nospace = ''
s = s.replace(space, nospace)
print s  # xxxxx-xxxxx
Ene Uran 638 Posting Virtuoso

Trapping a key event:

# bind keyevent to key down and display the key value

import wx

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

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

        self.Show(True)

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


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

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

# show different ways to specify colours with wxPython

import wx

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

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

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

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

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


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

Prey, good book I read about 5 years ago.

Interesting novel, has shades of the killer bees.

Ene Uran 638 Posting Virtuoso

Nano technology can potentially lead to human engineered miniature weapons that may spread like a bacterial infection in the enemy and get out of hand.

Too bad I am not a screen writer! I live just around the corner from many of the large movie studios here in LA, and that would make one heck of a scare movie!

Ene Uran 638 Posting Virtuoso

Not the easiest thing to do and depends heavily on your OS. Here is a DaniWeb snippet for the Windows OS:
http://www.daniweb.com/code/snippet399.html

The wxPython GUI toolkit also offers a printer widget.

Ene Uran 638 Posting Virtuoso

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

string = "hi"

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

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

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

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

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

import wx

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

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


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

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

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

import wx

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

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

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

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


from distutils.core import setup
import py2exe
import sys

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

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

Fuse,
I tested all the code in your tutorial for wxPython that you so kindly contributed to the new "Starting wxPython" sticky. The code examples work like a charm on my Windows Vista machine.

Ene Uran 638 Posting Virtuoso

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

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

Maybe we need a new sticky called "Starting wxPython" for the GUI programmers.

Ene Uran 638 Posting Virtuoso

I think you have to write it this way:
patternMatching(r"The|fox", 'The little brown fox')

Ene Uran 638 Posting Virtuoso

The wxPyton GUI toolkit has the fancier widgets for animation, graphics, plotting, sound and so on. If you are not at all familiar with GUI programming, Tkinter is a good way to start with and get the hang of it. Tkinter has a lot of sample code.

Ene Uran 638 Posting Virtuoso

If you have a computer made for the US market, you most likely don't have char 0156 (a hex number) in your character set.

Also note that editors like DrPython, SPE and UliPad screw up unicode character sets in their output window. Use PyScripter or ConText to get at least some order into playing with unicode.

Ene Uran 638 Posting Virtuoso
Ene Uran 638 Posting Virtuoso

I am using PyScripter more and more and really like the code completion, and the ease you can insert code templates.

For instance, hope it makes sense:

s = 'hello'
# Next line, the moment you type the period after s
# a code completion menu pops up
# with all the possible string functions.
# Here I doubleclicked on find.
# When I type the opening (  a popup hint comes up
# showing me what could go inside the find() function
# and more
ix = s.find('ll')
print ix

# Pressing ctrl/j brings up a template popup list
# for something like this
# Yes you can copy the result from the
# Pyscripter output/interpreter window
"""
my result -->
2
"""

One thing you have to be careful about is the use of running the code in memory (nice but dangerous) rather than from a saved file. Pyscripter has a tendency to quit unceremoniously with certain errors. If you didn't save a copy of your code, you lost it!

Ene Uran 638 Posting Virtuoso

LOL, I like to see the teacher's face if jimbox123 turns in slate's code as homework!

Ene Uran 638 Posting Virtuoso

Slate is right, his approach works with the old style class format:

>>> import types
>>> class Test: pass
... 
>>> t = Test()
>>> type(t) == types.InstanceType
True

But does not work with the new style class:

>>> import types
>>> class C(object): pass
... 
>>> c = C()
>>> type(c) == types.InstanceType
False
Ene Uran 638 Posting Virtuoso

Class instances have to be tested differently, since you also have to supply the class info (instance of what?):

>>> class Test:
...     pass
... 
>>> t = Test()
>>> type(t)
<type 'instance'>
>>> isinstance(t, Test)
True
>>>

If you use the new style class, this becomes more apparent:

>>> class Test(object):
...     pass
... 
>>> t = Test()
>>> type(t)
<class '__main__.Test'>
>>> isinstance(t, Test)
True
>>>
Ene Uran 638 Posting Virtuoso

I am curious what operating system you have. I have been trying to install PyQt4 on my Windows Vista machine and it seems to fail.

I downloaded PyQt-Py2.5-gpl-4.4.2-1.exe which is the Windows binary installer. It is supposed to contain everything needed for PyQt development except for Python itself:

PyQt
Qt (with database support for SQLite3 and ODBC)
Qt Designer
Qt Linguist
Qt Assistant
pyuic4
pylupdate4
lrelease
pyrcc4
QScintilla

However after the installation I get the notorious:
"ImportError: No module named PyQt4"
even though there is a PyQT4 folder and a bin subfolder with all the needed dll files in my Python Lib folder.

A shame, because PyQT sounds like and interesting GUI toolkit. Let me know what you did to make it work on your computer. If I get it to go, I can help you too.

More details, I downloaded:
http://www.riverbankcomputing.co.uk/static/Downloads/PyQt4/PyQt-Py2.5-gpl-4.4.2-1.exe

Don't ask me how I did it, but I got it to go on my Windows Vista machine. I started with the premise that the MS mindset is magnanimously screwed up. So here is the solution:
The PyQT installation works on Windows Vista if you add the file qt.conf found in C:\Python25 after the installation to (oh my God, what are those MS folks thinking?):
C:\Users\User_Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\PyQt GPL v4.4.2 for Python v2.5

You have to use your own User_Name!

Ene Uran 638 Posting Virtuoso

I too was trying to get the Eric IDE to go, but failed in my PyQT4 installation. See:
http://www.daniweb.com/forums/post618106-2.html

It may be my Windows Vista OS that throws in its childish security blocks on the installation.

Ene Uran 638 Posting Virtuoso

I am curious what operating system you have. I have been trying to install PyQt4 on my Windows Vista machine and it seems to fail.

I downloaded PyQt-Py2.5-gpl-4.4.2-1.exe which is the Windows binary installer. It is supposed to contain everything needed for PyQt development except for Python itself:

PyQt
Qt (with database support for SQLite3 and ODBC)
Qt Designer
Qt Linguist
Qt Assistant
pyuic4
pylupdate4
lrelease
pyrcc4
QScintilla

However after the installation I get the notorious:
"ImportError: No module named PyQt4"
even though there is a PyQT4 folder and a bin subfolder with all the needed dll files in my Python Lib folder.

A shame, because PyQT sounds like and interesting GUI toolkit. Let me know what you did to make it work on your computer. If I get it to go, I can help you too.

More details, I downloaded:
http://www.riverbankcomputing.co.uk/static/Downloads/PyQt4/PyQt-Py2.5-gpl-4.4.2-1.exe

Ene Uran 638 Posting Virtuoso

Well, if you get Eric to work, let the rest of us know what you did.

Ene Uran 638 Posting Virtuoso

They are pretty much useless if they do nothing else other than to boost up ones 'hard drive' temporarily.

If there is nothing on the 'hard drive', no drug will help, not even the usual caffeine (most popular energy drinks), hyper-breathing (oxygen) and tuna diet.

Ene Uran 638 Posting Virtuoso

$12 a gallon comes out high because the US Dollar is so devalued compared to the British Pound. Also the US Gallon is 3.8 liters. Even though $9 per gallon for petrol in the US would raise some eyebrows.

Ene Uran 638 Posting Virtuoso

Here is an example to make the tk window disappear:

import Tkinter as tk
import tkFileDialog

root = tk.Tk()
# show file dialog without Tkinter window
root.withdraw()

filename = tkFileDialog.askopenfilename()

print filename

To see the code tags around this code, temporarily click on the "REPLY W/QUOTE" button.

Ene Uran 638 Posting Virtuoso

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".

So what do you think the price of petrol will be in the US in 2012? If it's close to $20 a gallon it would be the end of the world!

Ene Uran 638 Posting Virtuoso

I am not quite sure what you mean with store, If you mean store in a string, there are these ways:

a=['city','village','town','capital']
a1=len(a)
a2=range(a1)
s = ""
for x in a2:
    a3=a[x]
    print a3
    s += a[x]

print s  # cityvillagetowncapital

Much simpler:

a=['city','village','town','capital']
s = ""
for x in a:
    s += x

print s  # cityvillagetowncapital

Add a space separator:

a=['city','village','town','capital']
s = ""
for x in a:
    s += x + " "  # add a space

print s  # city village town capital

Even simpler:

a=['city','village','town','capital']
s = " ".join(a)
print s  # city village town capital

Note: I hope Dani does not think those annoying HSBC popup ads are an improvement.

Ene Uran 638 Posting Virtuoso

In your scipy directory there is the package init file __init__.py and there also should be a __config__.py file. If not, you may have to reinstall or run the setup.py program.

python setup install
Ene Uran 638 Posting Virtuoso

Awesome. Thank you! the 0.2.0 beta works. I appreciate the help.

I am glad it works now. Where did you download the new beta version from?

Ene Uran 638 Posting Virtuoso

Interested in gasp?
See the post at:
http://www.daniweb.com/forums/post606877-137.html

Also take a look at the post from vegaseat on pygame just above that one.

Note: The missing function set_speed() sounds like something that would use pygame's clock() function. I heard the newer vesion 0.2.0 of gasp has incorporated clock().

Ene Uran 638 Posting Virtuoso

There are other functions missing too, like update_when(). Where did you get the code sample from? Maybe you have an outdated version of gasp.

Ene Uran 638 Posting Virtuoso

To find all functions/methods in a module like gasp use:

import gasp
print "List the functions within module gasp:"
for f in dir(gasp):
    print f

Look at the output, maybe it's just a minor spelling difference.

Info:
GASP (Graphics API for Students of Python) is a library built on pygame that enables absolute beginners to write 1980's style arcade games as an introduction to python

Ene Uran 638 Posting Virtuoso

CSV files are generated by spread sheet programs. Rows make a line in the file and the data columns are separated by commas. Python has a module called csv that makes processing this type of file much easier. Check the Python manual.

Ene Uran 638 Posting Virtuoso

There is too much brutality and suffering on this earth to imagine a "Loving God" looking down on this mess, and not helping to straighten things out.

Ene Uran 638 Posting Virtuoso

Something like this might do it:

import random

def dela(x):
    sum=0
    mylist = []
    while sum < x:
        b = random.randrange (1, x - sum + 1)
        mylist.append(b)
        sum = sum + b
        #print b,
    return sum, mylist

# test it ...
sum, mylist = dela(5)
print mylist  # eg. [2, 1, 1, 1]
Ene Uran 638 Posting Virtuoso

Please use code tags to mainain proper Python indentations!

def my_f(modelfilename):
    modelfile = open(modelfilename)
    modelline_list = modelfile.readlines()
    modelfile.close()

    itemY = ["lol", "young", "HoLa", "...", "Yum!",
        ":o)", "blokes", "!!!", "hello"]
    itemO = ["old", "yes", "Mom", "serious", "blog"]

    for line in modelline_list:
        for itemy in itemY:
            if itemy in line:
                print "+1 young"
                # not sure if this is what you want?
                return line  
            else:
                print "-1 old"
Ene Uran 638 Posting Virtuoso

Read line 8 and 9, you got to have the properly named icon image file for this to work.

Ene Uran 638 Posting Virtuoso

Give module subprocess a try, it's a bit more advanced:

import subprocess

# execute the code and pipe the result to a string
test = "ping xxx.xxx.xxx.xxx"
process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE)
# give it time to respond
process.wait()
# optional check (0 --> success)
print process.returncode  
# read the result to a string
result_str = process.stdout.read()
# test it ...
print result_str
Ene Uran 638 Posting Virtuoso

You can use a similar concept as shown in the entry case, using a name_list.

Ene Uran 638 Posting Virtuoso

With Python you can use the slicing operator to help out:

t1 = '1230'  # --> 12:30
t2 = '100'   # --> 1:00

# slicing operator seq[begin : end : step]
# step is optional
# defaults are index begin=0, index end=len(seq)-1, step=1
# -begin or -end --> count from the end backwards
# step = -1 reverses sequence
hr1 = t1[:-2]
mn1 = t1[-2:]
print hr1, mn1  # test --> 12 30


hr2 = t2[:-2]
mn2 = t2[-2:]
print hr2, mn2  # test -->  1 00
Ene Uran 638 Posting Virtuoso

If you insist on giving each entry field a recognizable name, you can try this:

# create named multi entries in Tkinter

import Tkinter as tk

class MyFrame(tk.Frame):
    """
    entries are in the same grid
    """
    def __init__(self, master):
        tk.Frame.__init__(self, master)

        words = ["one","two","three","four","five","six","seven","eight","nine"]
        # create a list of entries
        ent_list = []
        for w in words:
            ent_list.append(tk.Entry(self, width=6))

        # assign each entry in the list a grid position
        for ix, ent in enumerate(ent_list):
            ent.grid(row=ix, column=0)
            
        # rename the entries in the list
        for ix, ent in enumerate(ent_list):
            rename = "self.input_score_%s = ent" % words[ix]
            exec(rename)
            
        # create a test button
        tk.Button(self, text="press to test", command=self.test).grid()

        # frame
        self.grid()
        
    def test(self):
        # test it ...
        self.input_score_three.insert(0, "test3")
        self.input_score_eight.insert(0, "test8")

        
root = tk.Tk()
frame = MyFrame(root)
root.mainloop()
Ene Uran 638 Posting Virtuoso

Actually, Java and Python have a lot in common. Both languages compile to a bytecode that is then executed/interpreted with a virtual engine (JVM or PVM) specific to the operating system. Speeds are pretty comparable.

So yes, the only real difference is the syntax. An offspring of Python called Jython lets you use Python style syntax with Java libraries and compiles to Java bytecode. A happy marriage!

The power of the whole thing is that you can create Java bytecode with Python syntax. That will allow you to distribute your bytecode to just about any computer that is on the internet, since most browsers use the Java engine anyway. On top of that Jython is free and open source.

Ene Uran 638 Posting Virtuoso

There is actually a python code snippet on animated gifs and wxpython:
http://www.daniweb.com/code/snippet435.html

PyQT and QT use some rather complex legal stuff on licensing, so I don't use it!