Ene Uran 638 Posting Virtuoso

When the people you date are all virtual.

Ene Uran 638 Posting Virtuoso
Ene Uran 638 Posting Virtuoso

6+2x10 is easy
but
I oftened wondered what 7+2x10 could be

skilly commented: lol manaical +0
Ene Uran 638 Posting Virtuoso

Create a search for keywords file search utility. Something you can search all your code samples with. Might just be quite practical.

vegaseat commented: something like xfile +14
Lardmeister commented: yeah like xfind +10
Ene Uran 638 Posting Virtuoso

"Failure is simply an opportunity to begin again, this time more intelligently."
— Henry Ford

jingda commented: That's why you are so successful +0
Ene Uran 638 Posting Virtuoso

Henry Ford

"Thinking is the hardest work there is, which is probably the reason so few engage in it."

Ene Uran 638 Posting Virtuoso

Any seeds of today may contain the flowers of tomorrow.

e-papa commented: Good one. +0
Ene Uran 638 Posting Virtuoso

We have no right to assume that any physical laws exist, or if they have existed up to now, that they will continue to exist in a similar manner in the future.
-- Max Planck

Ene Uran 638 Posting Virtuoso

Science cannot solve the ultimate mystery of nature, for in the final analysis we ourselves are part of the mystery we are trying to solve.
-- Max Planck

Ene Uran 638 Posting Virtuoso

Write a star drawing program using the Tkinter GUI toolkit that comes with Python, or another GUI toolkit if you want to.

Ene Uran 638 Posting Virtuoso

"I can accept failure, everyone fails at something. But I can't accept not trying."
>> Michael Jordan

Ene Uran 638 Posting Virtuoso
e-papa commented: Thanks +1
Ene Uran 638 Posting Virtuoso

I give my vote to Amanda Peet

Ene Uran 638 Posting Virtuoso

3D Tic Tac Toe is free

Ene Uran 638 Posting Virtuoso

I like:
Spamming for Fairfax Homes
or
Spamming for windshield repair St Louis
or
Spamming for dentist new york

Have you no shame?

jephthah commented: haha +0
Ene Uran 638 Posting Virtuoso

I would tip a cow 10% and not a fraction more!

Ene Uran 638 Posting Virtuoso

I trained there and it didn't stop my drinking problem!

Ene Uran 638 Posting Virtuoso

Just a short explanation on how to create and access a Python package:

"""
assumes that you are using Python31 installed on the c drive
1) create a directory c:/Python31/MyModules
2) write an empty file __init__.py to that directory
   ( this makes MyModules a package)
3) write a test module module1.py to that directory
   ( has one code line --> text = "text from module1" )
4) test module module1.py in c:/Python31/MyModules
   with the code below, this file can be saved anywhere

since package directory MyModules is in the Python path
it will be found, remember package names are case sensitive
as are module names
"""

import MyModules.module1 as mm_module1

print(mm_module1.text)

Just change your drive and Python version as needed. On Linux you may need root permission.

Ene Uran 638 Posting Virtuoso

Sean Connery wore a toupee in every James Bond film that he starred in, beginning with Dr. No in 1962.

Ene Uran 638 Posting Virtuoso

That's why you should buy underwear that's yellow in front and brown in the back. :)

Anyway, yesterday I enjoyed some cherry ice cream and it had a part of a pit in it, enough to chip my tooth and now I have to spend some time at the dentist.

iamthwee commented: n1gga u iz 2 funny! +0
Ene Uran 638 Posting Virtuoso

Calm down, nobody has called you anything!

The thread caters to project ideas that are for the beginner. However beginners are at all sorts of levels in their learning progress. Any project takes some research, otherwise it isn't a project!

I have enjoyed the sticky's project ideas very much. Please put your clever Raffle project back into the thread. Avoid the unsubstantiated extra comments about other projects. If you manage to freeze up Python on a program you wrote, go to the regular forum and ask questions. This way you won't ask other folks to clutter up this nice thread/sticky with answers. That is what the rules imply.

It looks like the word Beginner should have been replaced by Python Enthusiast or something.

Ene Uran 638 Posting Virtuoso

This should tell DOS what kind of decoding you want to use:

# -*- coding: latin-1 -*-

print ord('é'.decode("latin-1"))     # 233
Ene Uran 638 Posting Virtuoso

Tired of pasta? This example shows you how to show an image file picture with IronPython's .NET GUI tools:

# show an image file using IronPython downloaded from:
# http://www.codeplex.com/ironpython
# modified the example from:
# http://www.voidspace.org.uk/ironpython/winforms/part11.shtml
# image PythonHand3.jpg is attached to post
# http://www.daniweb.com/forums/post958342.html#post958342
# tested with IronPython 2.6    by ene

import clr

clr.AddReference('System.Windows.Forms')
clr.AddReference('System.Drawing')

from System.Windows.Forms import (
    Application, DockStyle, Form, PictureBox, PictureBoxSizeMode
)
from System.Drawing import Image, Size

class MyForm(Form):
    def __init__(self):
        Form.__init__(self)
        # adjust the form's client area size to the picture
        self.ClientSize = Size(400, 300)
        # give the form a title
        self.Text = 'Explore the PictureBox()'

        # pick an image file you have in the working directory
        # or give full pathname
        fname = "PythonHand3.jpg"
        image = Image.FromFile(fname)
        pictureBox = PictureBox()
        # this will fit the image to the form
        pictureBox.SizeMode = PictureBoxSizeMode.StretchImage
        pictureBox.Image = image
        # fit the picture box to the frame
        pictureBox.Dock = DockStyle.Fill

        self.Controls.Add(pictureBox)
        self.Show()


form = MyForm()
Application.Run(form)
bumsfeld commented: very nice +11
vegaseat commented: thanks for the ironpython code +15
Ene Uran 638 Posting Virtuoso

Since a lot of wars are fought because of religious beliefs, it makes sense to apply a little religion to the weapons used.

Ene Uran 638 Posting Virtuoso

The Designer program that comes with the PyQt installations lets you drag and drop widgets on a form, modify properties and connect them. When done you save your work to a XML (.ui extension) file. You can load this XML file directly into a simple PyQt program and access it this way:

# run_combobox2.py
# a simple loader for .ui XML files generated with QTDesigner
# the XML file "combobox2.ui"
# contains a QWidget Form with a QComboBox on it
# the QComboBox signal is connected to the Form slot
# setWindowTitle(QString) via currentIndexChanged(QString)
# ene

import sys

from PyQt4 import QtGui, uic


app = QtGui.QApplication(sys.argv)
widget = uic.loadUi("combobox2.ui")
widget.show()

combo = widget.comboBox
# load the combobox with some string items
pasta_list = ['Spaghetti', 'Fettuccine', 'Ziti', 'Penne', 'Lasagne']
for pasta in pasta_list:
    combo.addItem(pasta)

app.exec_()

By the way, my XML file generated by the Qt Designer program looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Form</class>
 <widget class="QWidget" name="Form">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>392</width>
    <height>129</height>
   </rect>
  </property>
  <property name="font">
   <font>
    <family>Arial</family>
    <pointsize>12</pointsize>
   </font>
  </property>
  <property name="windowTitle">
   <string>Select a pasta from the combo box</string>
  </property>
  <widget class="QComboBox" name="comboBox">
   <property name="geometry">
    <rect>
     <x>20</x>
     <y>10</y>
     <width>181</width>
     <height>22</height>
    </rect>
   </property>
  </widget>
 </widget>
 <resources/>
 <connections>
  <connection>
   <sender>comboBox</sender>
   <signal>currentIndexChanged(QString)</signal>
   <receiver>Form</receiver>
   <slot>setWindowTitle(QString)</slot>
   <hints>
    <hint type="sourcelabel">
     <x>136</x>
     <y>21</y>
    </hint>
    <hint type="destinationlabel">
     <x>136</x>
     <y>45</y>
    </hint>
   </hints>
  </connection>
 </connections>
</ui>

You can see that the design information is all in there. If you are brave enough, you can carefully edit the XML file (leave the tags alone!) and …

Ene Uran 638 Posting Virtuoso

Okay, for a rough comparison here is the Tkinter GUI toolkit. Tkinter itself does not have a combo box widget, but the module ttk added since Python 3.1 has one:

# ttk_combobox3.py
# exploring the Tkinter expansion module ttk combobox
# tested with Python 3.1.1 and Tkinter 8.5
# ene

import tkinter as tk
import tkinter.ttk as ttk

def selection_changed(event):
    """a combo box item has been selected, show the item"""
    s = "You selected %s" % combo.get()
    root.title(s)

pasta_list = [
'Spaghetti',
'Vermicelli',
'Bucatini',
'Fettuccine',
'Linguine',
'Lasagne',
'Cavatappi',
'Manicotti',
'Macaroni',
'Penne',
'Rigatoni',
'Ziti',
'Farfalle',
'Spatzen',
'Orzo'
]

root = tk.Tk()
# window geometry is width x height + x_offset + y_offset
root.geometry("340x120+320+200")
root.title('Select a pasta from the combo box')

combo = ttk.Combobox()
# position the combobox
combo.place(x=10, y=10)
# bind selection to an action
combo.bind('<<ComboboxSelected>>', selection_changed)

# sort the pasta list
pasta_list = sorted(pasta_list)
# load the combo box with the pasta list
combo['values'] = pasta_list

# set the initial pasta
combo.set(pasta_list[0])

root.mainloop()
Ene Uran 638 Posting Virtuoso

I know it belongs in the wxPython sticky, but for comparison purposes here it is, the pasta combobox in wx code:

# wx_combobox1.py
# test the wxPython wx.ComboBox() widget
# wx.ComboBox(parent, id, value, pos, size, choices, style)
# a combination of a wx.TextCtrl() and a drop down listbox
# ene

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, pasta_list):
        wx.Frame.__init__(self, parent, id=-1,
            pos=(320, 200), size=(340, 120),
            title='Select a pasta from the combo box')
        panel = wx.Panel(self)
        panel.SetBackgroundColour("brown")

        self.pasta_list = sorted(pasta_list)
        self.combo = wx.ComboBox(panel, id=-1,
            value=self.pasta_list[0],
            pos=(10, 10), size=(150, 100),
            choices=self.pasta_list)
        # bind mouse click in the dropdown list to an action
        self.combo.Bind(wx.EVT_COMBOBOX, self.selection_changed)

    def selection_changed(self, event):
        """selected item has changed"""
        s = "Selected pasta is %s" % self.combo.GetValue()
        self.SetTitle(s)


pasta_list = [
'Spaghetti',
'Vermicelli',
'Bucatini',
'Fettuccine',
'Linguine',
'Lasagne',
'Cavatappi',
'Manicotti',
'Macaroni',
'Penne',
'Rigatoni',
'Ziti',
'Farfalle',
'Spatzen',
'Orzo'
]

app = wx.App(0)
# create a MyFrame instance and show it
MyFrame(None, pasta_list).Show()
app.MainLoop()
Ene Uran 638 Posting Virtuoso

It took a while, but I rewrote my pasta combobox program using Ironpython, not too bad if you know a little C#. PyQT is simpler code, but this one adds some color:

# ip_combobox1.py
# ironpython gives access to the Windows .NET or Linux Mono libraries
# download ironpython from:
# http://www.codeplex.com/ironpython
# ComboBox widget load items, select an item
# ene

import clr

clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")

import System
from System.Windows.Forms import *
from System.Drawing import *


class MyForm(System.Windows.Forms.Form):
    def __init__(self, pasta_list):
        self.initializeComponent()
        self.comboBox1.Sorted = True
        for item in pasta_list:
            self.comboBox1.Items.Add(item)
        # show first item
        self.comboBox1.Text = self.comboBox1.Items[0]

    def initializeComponent(self):
        self.comboBox1 = System.Windows.Forms.ComboBox()
        self.SuspendLayout()
        #
        # comboBox1
        #
        self.comboBox1.FormattingEnabled = True
        self.comboBox1.Location = System.Drawing.Point(12, 12)
        self.comboBox1.Name = 'comboBox1'
        self.comboBox1.Size = System.Drawing.Size(150, 26)
        self.comboBox1.TabIndex = 0
        self.comboBox1.SelectedValueChanged += \
            self.comboBox1_SelectedValueChanged
        #
        # Form1
        #
        self.BackColor = System.Drawing.Color.Brown
        self.ClientSize = System.Drawing.Size(323, 121)
        self.Controls.Add(self.comboBox1)
        self.Font = System.Drawing.Font('Courier New', 12.0,
            System.Drawing.FontStyle.Regular,
            System.Drawing.GraphicsUnit.Point, 0)
        self.Name = 'Form1'
        self.Text = 'Select a pasta from the combo box'
        self.ResumeLayout(False)

    def comboBox1_SelectedValueChanged(self, sender, e):
        """display present selction"""
        s = "Selected pasta is %s" % self.comboBox1.Text
        self.Text = s
        pass


pasta_list = [
'Spaghetti',
'Vermicelli',
'Bucatini',
'Fettuccine',
'Linguine',
'Lasagne',
'Cavatappi',
'Manicotti',
'Macaroni',
'Penne',
'Rigatoni',
'Ziti',
'Farfalle',
'Spatzen',
'Orzo'
]
Application.Run(MyForm(pasta_list))
Ene Uran 638 Posting Virtuoso

Bill Gates was riding a small private airplane in a remote region, along with some economists and a wilderness hiker. The hiker marveled that the world's smartest man was riding in the same plane.

All of a sudden, the pilot and copilot ran from the cockpit, grabbed two parachutes from the rack, and jumped out of the plane. Inspection showed the left engine was on fire, and that there were five people left on the plane, and four remaining parachutes.

They were discussing how to decide who got the parachutes, when Bill gates said, "The world needs my genius. He grabbed a pack and jumped out of the plane.

The hiker said, "I'm the least valuable, so the rest of you can go."

One of the economists then said, "That's not necessary. We have enough parachutes now. The world's smartest man just jumped out of the plane wearing your knapsack."

Ene Uran 638 Posting Virtuoso

Let's hope the lawyers are not winning in that one!

Ene Uran 638 Posting Virtuoso

It's as simple as this:

# convert a .png image file to a .bmp image file using PIL

from PIL import Image

file_in = "test1.png"
img = Image.open(file_in)

file_out = "test1.bmp"
img.save(file_out)
rasizzle commented: Great help. +1
maxvanden commented: very helpful +0
Ene Uran 638 Posting Virtuoso

A combobox is a selection widget that displays the current item, and can pop up a list of selectable items. It takes up a minimum amount of screen space.

# pqt_combobox1.py
# explore the PyQT QComboBox widget
# load, select
# ene

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class ComboBox(QWidget):
    def __init__(self, pasta_list, parent=None):
        QWidget.__init__(self, parent)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(320, 200, 340, 120)
        self.setWindowTitle('Select a pasta from the combo box')

        self.cb = QComboBox(self)
        self.cb.setFocusPolicy(Qt.NoFocus)
        self.cb.move(10, 10)
        # sort the list
        self.pasta_list = sorted(pasta_list)
        # load the combobox
        for pasta in self.pasta_list:
            self.cb.addItem(pasta)
        # bind/connect selection to an action
        self.connect(self.cb, SIGNAL('currentIndexChanged(QString)'),
            self.changedIndex)

    def changedIndex(self, value):
        """item in the combox has been changed/selected"""
        #print("value = %s" % value)  # test
        s = "You selected %s" % value
        self.setWindowTitle(s)


pasta_list = [
'Spaghetti',
'Vermicelli',
'Bucatini',
'Fettuccine',
'Linguine',
'Lasagne',
'Cavatappi',
'Manicotti',
'Macaroni',
'Penne',
'Rigatoni',
'Ziti',
'Farfalle',
'Spatzen',
'Orzo'
]

app = QApplication([])
cobo = ComboBox(pasta_list)
cobo.show()
app.exec_()
Ene Uran 638 Posting Virtuoso

There is some important information missing here. What module are you using/importing?

Also I have a dislike for people who post two threads on the same subject. That is very rude. Which one of your threads are we supposed to help with?

Ene Uran 638 Posting Virtuoso

Just testing out some of the many PyQT GUI toolkit widgets:

# explore PyQT QLineEdit, QPushButton, QLabel, QMessageBox,
# QHBoxLayout, QWidget, QMainWindow
# tested with Python 3.1.1 and PyQT 4.6.2.2
# ene

# easy import
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyWindow(QMainWindow):
    def __init__(self, parent= None):
        QMainWindow.__init__(self, parent)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(100, 150, 320, 100)
        self.setWindowTitle("Explore QLineEdit")
        self.create_widgets()

    def create_widgets(self):
        self.label = QLabel("Say hello:")
        self.edit = QLineEdit()
        self.button = QPushButton("Push Me!")
        # connect signal to button
        #QObject.connect(self.button, SIGNAL("clicked()"), self.on_click)
        # newer connect style used with PyQT 4.5+
        self.button.clicked.connect(self.on_click)

        # use horizontal layout
        h_box = QHBoxLayout()
        h_box.addWidget(self.label)
        h_box.addWidget(self.edit)
        h_box.addWidget(self.button)
        # create central widget, add layout and set
        central_widget = QWidget()
        central_widget.setLayout(h_box)
        self.setCentralWidget(central_widget)

    def on_click(self):
        """the button has been clicked"""
        msg = "Good day %s" % self.edit.displayText()
        QMessageBox.information(self, "Title", msg, QMessageBox.Ok)


# test potential module
if __name__ == "__main__":
    app = QApplication([])
    window = MyWindow()
    window.show()
    app.exec_()
Ene Uran 638 Posting Virtuoso

Age is strictly a case of mind over matter. If you don't mind, it doesn't matter.
-- Jack Benny

Ene Uran 638 Posting Virtuoso

Xmas dances and music

Ene Uran 638 Posting Virtuoso

Here is the code to sort a dictionary of dictionaries:

# sorted display of a dictionary of dictionaries

def dict_of_dict_sort(dd, key):
    """
    print out selected items from a dictionary of dictionaries dd
    sorted by a given key
    """
    for k in sorted(dd, key=lambda x: dd[x][key]):
        print( k, dd[k]['age'], dd[k]['country'] )


user_dict = {
'Bill': {'age': 39, 'country': 'USA'},
'Dave' : {'age': 26, 'country': 'Canada'},
'Olaf' : {'age': 33, 'country': 'Sweden'}
}

# display sorted by age
dict_of_dict_sort(user_dict, 'age')

"""my result -->
Dave 26 Canada
Olaf 33 Sweden
Bill 39 USA
"""
Ene Uran 638 Posting Virtuoso

This problem has been around for a long time and not just with Python:

# the "Microsoft kludge", quoting a string within a string fixes the 
# space-in-folder-name problem, tells the OS to use the whole string
# including spaces as a single command
# (make sure filename does not contain any spaces!)
os.system('"C:/Program Files/IrfanView/i_view32.exe" ' + filename)
JasonHippy commented: Nicely done....How did I miss that?! +4
Gribouillis commented: nice trick +5
pysup commented: Perfect +1
Ene Uran 638 Posting Virtuoso

It easier to make fun of something you don't understand, than trying to understand it.

For instance a frequent phrase used by US politicians:
"The Canadian and British Health Care System is a complete failure."

If you say it often enough it becomes the truth!

Ene Uran 638 Posting Virtuoso

Try something like this:

label = list(range(len(files)))
    for k, fname in enumerate(files):
        image = Image.open(filedir+"/"+fname)
        ##((width, height))
        image.thumbnail((160, 240))
        photo = ImageTk.PhotoImage(image)
        label[k] = Label(image=photo)
        label[k].image = image # keep a reference!
        #label[k].pack()  # pack when you want to display it


        #print files
    return ...
Param302 commented: Thank you so much, I want to display multiple images, but today I have seen you have figured it out 11 years ago, really thank you so much! +0
Ene Uran 638 Posting Virtuoso

See if something like this will do, but be careful that all the slicing doesn't steal some data:

def extract_number(data_str):
    """
    extract the numeric value from a string
    (the string should contain only one numeric value)
    return the numeric part of the string or None
    """
    s = ""
    for c in data_str:
        if c in '1234567890.-':
            s += c
    if s:
        return s
    else:
        return None


def extract_between(text, sub1, sub2):
    """
    extract a substring from text between first
    occurances of substrings sub1 and sub2
    """
    return text.split(sub1, 1)[-1].split(sub2, 1)[0]


# test file
fname = "violate.dat"

mylist = []
flag = False
for line in open(fname):

    if flag == True:
        mylist.append(line)
        flag = False
    if "FCITC" in line:
        flag = True

newlist = []
for item in mylist:
    temp1 = item[:16]
    #print(temp1)  # test
    temp1 = extract_number(temp1)

    temp2 = item[35:83]
    #print(temp2)  # test
    temp2 = temp2[6:28].replace(']', ' ')
    temp2 = temp2.strip()
    #print(temp2)  # test

    temp3 = item[96:144]
    #print(temp3)  # test
    temp3 = extract_between(temp3, '[B]', '[/B]').rstrip()
    #print(temp3)  # test

    newlist.append((temp1, temp2, temp3))


print('-'*40)

for tup in newlist:
    print(tup)

"""my show -->
('690.4', '5567 IND RIV      115', 'Base Case')
('-756.5', '6106 I-STATE      230', '7890 OSCEOLA      230   9190 AGNES-RX')
('589.3', '5704 TAFT         230', ' 2883 INTERCSN     230   5352 CAN ISL')
('1905.9', '6101 MCINTOSH     230', ' 9100 RECKER       230   9150 LKAGNES')
('1119.9', '2167 WINDERME     230', '5353-5800')
('-1121.7', '467 POINSETT     230', '351 ORANGE R     230    354 ORANGE R')
('1776.3', '461 CAPE K       230', '461 CAPE K       230   5703 IND RIV')
('899.9', '5704 TAFT         230', …
majestic0110 commented: nice answer! +5
Ene Uran 638 Posting Virtuoso

There is another Python version called IronPython that uses Python syntax. It runs independent from the normal CPython version and allows access to the large GUI libraries of .NET and Mono. Here is an example:

# create a window with a button and click event using ironpython
# ironpython gives access to the Windows .NET or Linux Mono libraries
# download ironpython from:
# http://www.codeplex.com/ironpython
# tutorial at:
# http://www.zetcode.com/tutorials/ironpythontutorial/
#
# to distinguish the filename from normal Python use prefix ip_
# if you save this file as "ip_buttonWin1.py"
# compile it with something like:
# C:\IronPython 2.6\ipy.exe "ip_buttonWin1.py"
#
# clr -> Common Language Runtime

import clr

clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")

from System.Windows.Forms import Application, Form, Button, ToolTip
from System.Drawing import Size, Point

class IForm(Form):

    def __init__(self):
        # set form title, position, size
        self.Text = 'Button'
        self.CenterToScreen()
        self.Size = Size(300, 150)

        btn = Button()
        btn.Parent = self
        btn.Text = "Quit"
        btn.Location = Point(50, 50)
        # click on the button to call OnClick()
        btn.Click += self.OnClick
        # mouse over button calls OnEnter()
        btn.MouseEnter += self.OnEnter

        # optional tooltip
        tooltip = ToolTip()
        # tooltip for the button
        tooltip.SetToolTip(btn, "Don't be a Quitter")

    def OnClick(self, sender, args):
        self.Close()

    def OnEnter(self, sender, args):
        #print sender, type(sender)
        self.Text = "mouse entered button area"


Application.Run(IForm())

Since i have a Windows XP machine I installed
IronPython-2.6.msi
and for the .NET framework (free from MicroSoft)
NetFx20SP1_x86.exe

See the details in file Readme.html that comes with the installation.

Lardmeister commented: useful +10
Ene Uran 638 Posting Virtuoso

A similar table, this time we use PyQT's QTableView and QAbstractTableModel which allows the items in the table to be sorted by simply clicking on the header titles:

# use PyQT's QTableView and QAbstractTableModel
# to present tabular data
# allow sorting by clicking on the header title
# tested with Python 3.1.1 and PyQT 4.5.2
# ene

import operator
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyWindow(QWidget):
    def __init__(self, data_list, header, *args):
        QWidget.__init__(self, *args)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(300, 200, 420, 250)
        self.setWindowTitle("Exploring PyQT's QTableView")

        table_model = MyTableModel(self, data_list, header)
        table_view = QTableView()
        table_view.setModel(table_model)
        # enable sorting
        table_view.setSortingEnabled(True)

        layout = QVBoxLayout(self)
        layout.addWidget(table_view)
        self.setLayout(layout)


class MyTableModel(QAbstractTableModel):
    def __init__(self, parent, mylist, header, *args):
        QAbstractTableModel.__init__(self, parent, *args)
        self.mylist = mylist
        self.header = header

    def rowCount(self, parent):
        return len(self.mylist)

    def columnCount(self, parent):
        return len(self.mylist[0])

    def data(self, index, role):
        if not index.isValid():
            return QVariant()
        elif role != Qt.DisplayRole:
            return QVariant()
        return QVariant(self.mylist[index.row()][index.column()])

    def headerData(self, col, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return QVariant(self.header[col])
        return QVariant()

    def sort(self, col, order):
        """sort table by given column number col"""
        self.emit(SIGNAL("layoutAboutToBeChanged()"))
        self.mylist = sorted(self.mylist,
            key=operator.itemgetter(col))
        if order == Qt.DescendingOrder:
            self.mylist.reverse()
        self.emit(SIGNAL("layoutChanged()"))


header = ['First Name', 'Last Name', 'Age', 'Weight']
# a list of (name, age, weight) tuples
data_list = [
('Heidi', 'Kalumpa', '36', '127'),
('Frank', 'Maruco', '27', '234'),
('Larry', 'Pestraus', '19', '315'),
('Serge', 'Romanowski', '59', '147'),
('Carolus', 'Arm', '94', '102'),
('Michel', 'Sargnagel', '21', '175')
]

app = QApplication([])
win = MyWindow(data_list, header)
win.show()
app.exec_()

Not sure what is going on …

Ene Uran 638 Posting Virtuoso

Thanks vegaseat for the newer PyQT style info. Here is a relatively simple way to display tabular data using a function to create an html coded table:

# PyQT's QLabel widget can display html formatted text
# used here to display data in a nice table
# tested with Python 3.1.1 and PyQT 4.5.2
# ene

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyForm(QWidget):
    def __init__(self, html_table):
        QWidget.__init__(self)
        # setGeometry(x_pos, y_pos, width, height)
        # widget will expand to fit lable size
        self.setGeometry(100, 150, 1, 1)
        self.setWindowTitle("html formatted data table")

        label = QLabel(html_table)

        # use the grid layout manager
        grid = QGridLayout()
        # addWidget(widget, row, column, rowSpan=1, columnSpan=1)
        grid.addWidget(label, 0, 0)
        self.setLayout(grid)


def make_html_table(data_list):
    """
    use a list of data tuples and create the html code
    of a html formatted table containing the data items
    """
    rows = len(data_list)
    columns = len(data_list[0])
    # color is in hex format "#RRGGBB"
    html = '<table border="5" bordercolor="#0000cc" cellspacing="5" '
    html += 'cellpadding="5" width="5" bgcolor="#ffff66">\n'
    for row in range(rows):
        html += '<tr>\n'
        for col in range(columns):
            item = data_list[row][col]
            html += "    %s%s%s\n" % ('<td>', item, '</td>')
        html += '</tr>\n'
    html += '</table>\n'
    return html


# a list of (name, age, weight) tuples
# the first tuple is the header
data_list = [
('Name', 'Age', 'Weight'),
('Heidi Kalumpa', '36', '127'),
('Frank Maruco', '27', '234'),
('Larry Pestraus', '19', '315'),
('Serge Romanowski', '59', '147'),
('Carolus Arm', '94', '102'),
('Michel Sargnagel', '21', '175')
]

html_table = make_html_table(data_list)

#print(html_table)  # for test only

app =  QApplication([]) …
Ene Uran 638 Posting Virtuoso

Look over this code sample, it should be very explanatory:

# role of self in Python classes
# self can be named different, but 'self' is convention

class Snake:
    def __init__(self, name):
        # self keeps track of each instance
        # and also makes self.name global to class methods
        self.name = name
        # test
        print(self)

    def isnice(self):
        # a class method has self as the first argument
        return self.name + " is very nice"

# create 2 instances of class Snake
bob = Snake('Bob Python')
mary = Snake('Mary Rattle')

print('-'*40)

# now you can get the name that has been assigned to self.name
print(bob.name)
print(mary.name)

# access the class method
print(mary.isnice())

"""my result -->
# self for each instance has a different location in memory
<__main__.Snake object at 0x01E0B2B0>
<__main__.Snake object at 0x01E0B090>
----------------------------------------
Bob Python
Mary Rattle
Mary Rattle is very nice
"""
vegaseat commented: very nice +14
Ene Uran 638 Posting Virtuoso

This simple Python code uses the Tkinter GUI toolkit and the Python Image Library (PIL) to create a program that allows you to grab an image of the display screen (or portion of it) and save it to an image file. Unfortunately, the ImageGrab.grab() method only works on a Windows computer. Sorry about that to all you good folks using PC Linux or Apple Unix. I guess we have to ask the PIL folks to get on the ball!

Ene Uran 638 Posting Virtuoso

You can download the matplotlib free from: http://matplotlib.sourceforge.net/
It has, amongst many other things, the module pylab that allows for high quality plotting of data. All you have to do is to feed it a list of x values and the corresponding list of y values calculated from the x data and you are ready to enjoy the plot in its separate window/frame. From there you can zoom the graph, drag the graph, change the margins, and save the graph to a popular image file like PNG.

Ene Uran 638 Posting Virtuoso

Just a simple console blackjack game. The bread and butter code was written with lots of comments, so you can improve on it. Really, the most important part is figuring out when an ace is 11 in value and when it is a 1 in value, so you don't bust.

Ene Uran 638 Posting Virtuoso

More or less a templet database that allows you to load, save, add, list, search, edit and delete data items. I used movies as an example, but you can easily change that to make a database of many other things.

Ene Uran 638 Posting Virtuoso

The .h in windows.h stands for header, it is actually C not html. Header files are there to unclutter your code and make it easier to read and hopefully understand. So by nature, header files are hard to read and understand for a beginner.