Putting the lyrics to the 99BoB song into a PyQT listbox is simple and much fun ...
I am getting a lot of double posting lately. sorry!
Putting the lyrics to the 99BoB song into a PyQT listbox is simple and much fun ...
I am getting a lot of double posting lately. sorry!
Putting the lyrics to the 99BoB song into a PyQT listbox is simple and much fun ...
# add '99 bottles of beer' lyrics to a PyQT list box
# tested with PyQT 4.5.2 and Python 3.1.1
# just for the fun of it vegaseat
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MyWindow(QWidget):
def __init__(self):
QWidget.__init__(self)
# setGeometry(x_pos, y_pos, width, height)
self.setGeometry(100, 150, 280, 360)
self.setWindowTitle("99 Bottles of Beer")
self.count = 1
layout = QVBoxLayout(self)
self.list = QListWidget(self)
layout.addWidget(self.list)
s = 'show 99 bottles of beer lyrics'
self.button = QPushButton(s, self)
layout.addWidget(self.button)
# old connect style for PyQt < 4.5
#self.connect(self.button, SIGNAL('clicked()'), self.showSong)
# new connect style for PyQt 4.5+
self.button.clicked.connect(self.showSong)
def showSong(self):
bottle = "\n%s bottle"
beer = "s of beer on the wall!"
take = "!\nTake one down, pass it around,"
for k in range(99, 0, -1):
# an exercise in slicing
s1 = ((bottle % k + beer[k==1:])*2)[:-13]
s2 = bottle % (k-1 or "No")
s3 = beer[k==2:-1] + "!"
self.list.addItem(s1 + take + s2 + s3)
app = QApplication([])
window = MyWindow()
window.show()
app.exec_()
“Ego is the immediate dictate of human consciousness.”
-- Max Planck
"PC Helpline, how may I help you?"
"Yes, well, I'm having trouble with WordPerfect."
"What sort of trouble?"
"Well, I was just typing along, and all of a sudden the words went away."
"Went away?"
"They disappeared."
"Hmm. So what does your screen look like now?"
"Nothing."
"Nothing?"
"It's blank; it won't accept anything when I type."
"Are you still in WordPerfect, or did you get out?"
"How do I tell?"
"Can you see the C:\> prompt on the screen?"
"What's a sea-prompt?"
"Never mind. Can you move the cursor around on the screen?"
"There isn't any cursor: I told you, it won't accept anything I type."
"Does your monitor have a power indicator?"
"What's a monitor?"
"It's the thing with the screen on it that looks like a TV. Does it have a
little light that tells you when it's on?"
"I don't know."
"Well, then look on the back of the monitor and find where the power cord
goes into it. Can you see that?"
[sound of rustling and jostling then muffled]
"Yes, I think so."
"Great! Follow the cord to the plug, and tell me if it's plugged into the
wall."
"Yes, it is."
"When you were behind the monitor, did you notice that there were two
cables plugged into the back of it, not just one?"
…
These two strings walk into a bar and sit down.
The bartender says, "So what'll it be?"
The first string says, "I think I'll have a beer quag fulk boorg jdkCjfdLk jk3s d#f67howeU r89nvyowmc63Dz x.xvcu"
"Please excuse my friend," the second string says, "He isn't null-terminated."
Due to the bad state of the economy Exxon-Mobile has just laid off another 25 Congressmen.
A scientific truth does not triumph by convincing its opponents and making them see the light, but rather because its opponents eventually die and a new generation grows up that is familiar with it.
-- Max Planck
... when the birds you watch are in a tree.
"The most terrifying words in the English language are: I'm from the government and I'm here to help."
-- Ronald Reagan
If you want to pass arguments to an action function during a button click with the PyQt GUI toolkit, you can use a similar arrangement utilized with the Tkinter GUI toolkit ...
# pqt_Button_lambda1.py
# exploring PyQT's QPushButton button widget
# pass each button's argument using lambda
# vegaseat
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MyForm(QWidget):
def __init__(self):
QWidget.__init__(self)
# create the widgets
self.button1 = QPushButton("button1")
self.button2 = QPushButton("button2")
s = '<>'*10
self.label = QLabel(s)
# use grid layout for the widgets
grid = QGridLayout()
grid.addWidget(self.button1, 0, 0)
grid.addWidget(self.button2, 1, 0)
grid.addWidget(self.label, 2, 0)
self.setLayout(grid)
# connect the buttons to an action with arg passing
action1 = lambda: self.onclick("button1 clicked")
self.connect(self.button1, SIGNAL("clicked()"), action1)
action2 = lambda: self.onclick("button2 clicked")
self.connect(self.button2, SIGNAL("clicked()"), action2)
def onclick(self, s):
self.label.setText(s)
app = QApplication([])
form = MyForm()
form.show()
app.exec_()
Tkinter ref: http://www.daniweb.com/forums/post1077620.html#post1077620
You know you are a computer geek when this makes sense to you:
Roses are #FF0000, Violets are #0000FF.
Sounds delicious, where can I get one? :)
Bad or missing mouse driver. Spank the cat [Y/N]?
What kind of layout manager are you using?
What have you tried so far?
If you want to display the result you have to use a GUI toolkit like PyQt. The PyQt label widget can display html formatted text like this example shows:
http://www.daniweb.com/forums/post1093216.html#post1093216
In ene's earlier post she mentioned that the PyQt label can display hmtl code. This can be used to display scientific text that has sub and superscripts ...
# PyQT's QLabel widget can display html formatted text
# tested with Python 3.1.1 and PyQT 4.6.1
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MyForm(QWidget):
def __init__(self, html_code):
QWidget.__init__(self)
# setGeometry(x_pos, y_pos, width, height)
# 1, 1 --> widget will expand to fit lable size
self.setGeometry(100, 150, 1, 1)
self.setWindowTitle("html formatted text")
label = QLabel(html_code)
# use the grid layout manager
grid = QGridLayout()
# addWidget(widget, row, column, rowSpan=1, columnSpan=1)
grid.addWidget(label, 0, 0)
self.setLayout(grid)
# <H3> and </H3> tags set text size
html_code = """\
<H3>
you can do scientific text like this ...
<BR>
H<sub>2</sub>O
<BR>
x<sup>3</sup> + y<sup>2</sup> - 15 = 0
</H3>
"""
app = QApplication([])
form = MyForm(html_code)
form.show()
app.exec_()
Spamming comprises some 80 to 85% of all the email in the world. Yes, that sick stuff is going on right here on DaniWeb too in the form of signature spams.
I can't understand how anyone would push their meager wares by annoying the potential customer.
You are reading lines of the text file, not individual words. To get to the individual word study this hint ...
line = "Toto je moj prvy pokus otvorit a citat subor."
word_list = line.split()
for word in word_list:
print word
Note:
Please use code tags with your code to preserve the indentations. Otherwise the code is very difficult to read and not too many folks will help.
Here is a classic Chomsky sentence writer. Your mission will be to customize the data using for instance some of your boss's latest memos.
"""
An aid to writing linguistic papers in the style of Noam Chomsky.
It is based on selected phrases taken from actual books and articles
written by the great master. Upon request, it assembles the phrases
in the elegant stylistic patterns that Chomsky was noted for.
You are encouraged to add more patterns.
To generate n sentences of linguistic wisdom, type ...
chomsky(n)
chomsky(5) generates about half a screen of linguistic truth
modified to work with Python2 and Python3
"""
import textwrap
import random
from itertools import chain, islice
def chomsky(n=1, line_length=72):
"""
put it all together Noam Chomsky style, n = number of sentences
"""
parts = []
for part in (leadins, subjects, verbs, objects):
phrase_list = [x.strip() for x in part.splitlines()]
random.shuffle(phrase_list)
parts.append(phrase_list)
output = chain(*islice(zip(*parts), 0, n))
return textwrap.fill(' '.join(output), line_length)
# 'lead ins' to buy some time ...
leadins = """\
To characterize a linguistic level L,
On the other hand,
This suggests that
It appears that
Furthermore,
We will bring evidence in favor of the following thesis:
To provide a constituent structure for T(Z,K),
From C1, it follows that
Analogously,
Clearly,
Note that
Of course,
Suppose, for instance, that
Thus
With this clarification,
Conversely,
We have already seen that
By combining adjunctions and certain deformations,
I suggested that these results would follow from the assumption that
However, this assumption is …
Looks like classic Chomsky generated text! Those things are fun to work with.
Did you know you could do that with the module os?
# using Python module os to create random values
import os
n = 35
# returns a string of n random bytes
random_bytes = os.urandom(n)
# some bytes may not be printable
# so create a string of all the printable bytes
random_str = ""
for byt in random_bytes:
# select ascii printable bytes/characters
if 32 < ord(byt) < 127:
random_str += byt
print(random_str)
for k in range(10):
# random integer from 0 to 255
random_integer = ord(os.urandom(1))
print(random_integer)
Go through all the Python module os functions and write an example code for each.
An honest politician, a kind lawyer and Santa Claus walked through a very posh hotel lobby. There, in front of them, was a $100 Dollar bill lying on the floor. Which one picked it up?
!tsixe t'nod owt rehto eht ,esruoc fo atnaS
"I stopped believing in Santa Claus when I was six. Mother took me to see him in a department store, and he asked me for my autograph."
-- Shirley Temple
Here is an example ...
# example of methods you can override/overload in classes
# __str__() overloads str() as applied to the class instance
# note that print or print() uses str()
class Dollars(object):
def __init__(self, amount):
self.amount = amount
def __str__(self):
return "You owe me $%s" % str(self.amount)
a = 10
print( a ) # 10
# create a class instance
dollar = Dollars(10)
print( dollar ) # You owe me $10
This is an update of an earlier version. In this version the string containing the approximated pi value is created directly from the iteration of the generator. This way the program is simplified and can be used with Python2 and Python3 ...
As of feb2007 the pi approximation record is 1,241,100,000,000 digits.
The Python module time has many interesting functions to process date and time related problems. Here is an example that shows how you can switch one date format to another format ...
# convert one time format to another
import time
date_old = "08-Jan-2009"
# use strptime(string, format_str) to form a time tuple
# (year,month,day,hour,min,sec,weekday(Monday=0),yearday,dls-flag)
time_tuple = time.strptime(date_old, "%d-%b-%Y")
# use time.strftime(format_str, time_tuple) to create new format
date_new = time.strftime("%m/%d/%y", time_tuple)
print( "New format = %s" % date_new )
print( "Old format = %s" % date_old )
print( "Time_tuple = %s" % time_tuple )
"""my output -->
New format = 01/08/09
Old format = 08-Jan-2009
Time tuple = (2009, 1, 8, 0, 0, 0, 3, 8, -1)
"""
My contribution to cheer up A.D.
Life is pleasant. Death is peaceful. It’s the transition that’s troublesome.
— Isaac Asimov
Pulling usable code out the wxPython demo code is a royal pain. However, there are a lot of nicely working examples here:
http://www.daniweb.com/forums/thread128350.html
Tell us which widget of the demo you are interested in and we can try to help.
"Gentlemen prefer bonds."
-- Andrew Mellon
Combinations and Permutations are closely linked. The function shown here is a recursive generator function that returns permutations with selectable sample size ...
# a permutation or combination does not repeat sample items
# Python3 has a non-recursive combination function
# via itertools.combinations(iterable, sample_size)
# and a non-recursive permutation function
# via itertools.permutations(iterable, sample_size=None)
# vegaseat
def permutations(seq, n):
"""
permutations(seq, n) is a recursive generator function where
seq is an iterable object like a list or string
n is the sample size
returns a list of nonrepeating sample size items
n = len(seq) is the max sample size
"""
if n == 0:
yield []
else:
for k in range(len(seq)):
# a recursive function
for p in permutations(seq[:k] + seq[k+1:], n - 1):
yield [seq[k]] + p
def unique_combinations(seq, n):
"""
unique_combinations(seq, n) is a recursive generator function
where
seq is an iterable object like a list or string
n is the sample size
returns a list of nonrepeating sample size items
n = len(seq) is the max sample size
"""
if n == 0:
yield []
else:
for i in range(len(seq) - n + 1):
# recursion
for uc in unique_combinations(seq[i+1:], n - 1):
yield [seq[i]] + uc
iterable = 'abc'
sample_size = 2
perm_list = list(permutations(iterable, sample_size))
# show as a list of lists
print( perm_list )
print( '-'*40 )
# show as a list of strings
print( ["".join(item) for item in perm_list] )
print( '-'*40 )
comb_list = list(unique_combinations(iterable, sample_size))
# show as a list …
To illustrate the basics ...
mystr = "abcdefg"
print type(mystr)
print mystr
print mystr[-2:-1]
print '-'*10
mylist = ['fred', 'peter', 'gustav', 'george']
print type(mylist)
print mylist
print mylist[-2:-1]
"""my output -->
<type 'str'>
abcdefg
f
----------
<type 'list'>
['fred', 'peter', 'gustav', 'george']
['gustav']
"""
Paralyze resistance with persistence.
-- Woody Hayes
I've always liked Atlanta. And not just for the strip clubs, but the shopping and the food.
-- Jon Stewart
Is it as good as the Muppet movie at Disney World?
With the economy still in a hangover I doubt that a few flimsy decorations will inspire shoppers to shop in the land of "Made In China" goods.
Xmas is the time when you sit in front of a dead tree and hope that some obese senior citizen will bring presents down the chimney.
As woooee already mentioned, don't use the Python Shell (has those screwy looking >>> prompts) for writing programs. The Shell is only used for testing small parts of code.
You can modify woooee's code ...
import os
a = []
a = os.listdir('.')
for t in a:
if os.path.isfile(t):
f = open(t,'r')
print t, "opened"
data_str = f.read()
# do something with the data string later ...
f.close()
# break here if you only want the first file
break
else:
print " ", t, "not a file"
# now process your data string
Which version of Python are you using?
Using Python2 you would use something like this to create an array of names. Generally Python uses lists for arrays.
# create the name list
name_list = []
while True:
name = raw_input("Enter your name (q to quit): ")
if name.lower() == 'q':
break
name_list.append(name)
# show the name_list contents
for name in name_list:
print name
With numbers you can do something similar ...
# create the number list (int or float)
number_list = []
while True:
number = input("Enter a number (-99 to quit): ")
if number == -99:
break
number_list.append(number)
# show the number_list contents
for number in number_list:
print number
If you want to enter a fixed number of numbers, use a for loop ...
# create the number list (int or float)
number_list = []
for k in range(5):
number = input("%d) Enter a number : " % (k+1))
number_list.append(number)
# show the number_list
for number in number_list:
print number
hondros -
thank you, this helps alot! ill have a tinker and see if i can get it running :D
Don't forget to set a and b to zero outside the loop.
You might want to use bind() rather then the command arg. Take a look at:
http://www.daniweb.com/forums/showthread.php?p=1077620#post1077620
Using the Tkinter GUI toolkit, the question of how to detect which button has been clicked comes up often. There are several solutions. The first solution is to use the bind() method that passes an event ...
# using the bind event to detect the widget clicked
# vegaseat
from Tkinter import *
def click(event):
"""detects the text/label of the button clicked via event"""
if event.widget.cget("text") == "one":
root.title("Button one has been clicked")
elif event.widget.cget("text") == "two":
root.title("Button two has been clicked")
root = Tk()
b1 = Button(text="one")
# bind passes an event to function click
b1.bind("<Button-1>", click)
b1.pack(padx=150)
b2 = Button(text="two")
b2.bind("<Button-1>", click)
b2.pack()
root.mainloop()
Other solutions rely on passing an argument to the function used with the button command. Usually the command only accepts a reference to the function. Here are three different ways to get past this obstacle ...
# using lambda to pass command arguments
# vegaseat
from Tkinter import *
def click(s):
"""called with lambda"""
if s == "one":
root.title("Button one has been clicked")
else:
root.title("Button two has been clicked")
root = Tk()
b1 = Button( text="one", command=lambda: click("one") )
b1.pack(padx=150)
b2 = Button( text="two", command=lambda: click("two") )
b2.pack()
root.mainloop()
... another ...
# using a closure to pass command arguments
# vegaseat
from Tkinter import *
def click(s):
"""a typical closure, a function within a function"""
def inner_click():
if s == "one":
root.title("Button one has been clicked")
else:
root.title("Button two has been clicked")
return inner_click
root = Tk()
b1 = Button( …
A Tkinter resizing example that shows two frames on a frame that in this case respond differently to the resizing of the main window ...
# experiments with Tkinter resizing
# two frames on a frame, keep one frame height fairly constant
# vegaseat
try:
# Python2
import Tkinter as tk
except ImportError:
# Python3
import tkinter as tk
class MyApp(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master, bg='yellow')
self.prepare_resizing()
# set the title, self.top is from prepare_resizing()
# and is actually the master in this case
self.top.title("Two Frames (resize the window)")
self.make_widgets()
def prepare_resizing(self):
""" needed for stretch/resize """
self.grid(sticky='nswe')
self.top = root.winfo_toplevel()
self.top.rowconfigure(0, weight=1)
self.top.columnconfigure(0, weight=1)
# there are two rows in this example
# set row ratios
self.rowconfigure(0, weight=1)
# make weight for row 1 very high to keep row 0 constant
self.rowconfigure(1, weight=1000)
# there is only one column in this example
self.columnconfigure(0, weight=1)
def make_widgets(self):
# put frame1 in row 0 to keep it fixed in height
frame1 = tk.Frame(self, bg='brown', width=400, height=50)
frame1.grid(row=0, column=0, sticky='nesw')
# needed for width and height
frame1.grid_propagate(0)
# need for button to stick 'w'
frame1.columnconfigure(0, weight=1)
# put frame2 in row 1 to make it resize
frame2 = tk.Frame(self, bg='green', width=400, height=200)
frame2.grid(row=1, column=0, sticky='nesw')
# needed for width and height
frame2.grid_propagate(0)
# need for button to stick 'e'
frame2.columnconfigure(0, weight=1)
b1 = tk.Button(frame1, text="Frame1 Button1")
# this grid is inside frame1
b1.grid(row=0, column=0, padx=5, pady=10, sticky='w')
b2 = tk.Button(frame2, text="Frame2 Button2")
b2.grid(row=0, column=0, padx=5, pady=10, sticky='e')
root = tk.Tk() …
Something like this works ...
# main program firstscript.py
# display an image using Tkinter and PIL
# PIL allows Tkinter to read more than just .gif image files
import Tkinter as tk
from PIL import ImageTk
def next_image():
import secondscript
root = tk.Tk()
# size the window so the image will fit
root.geometry("%dx%d+0+0" % (360, 240))
# create all image objects in __main__ to be persistent
# pick an image file you have in your working directory
# or specify full path
image_file = "people1.bmp"
photo = ImageTk.PhotoImage(file=image_file)
root.title(image_file)
# put the image on a canvas
cv = tk.Canvas()
cv.pack(side='top', fill='both', expand='yes')
cv.create_image(0, 0, image=photo, anchor='nw')
# now add a button on top of the canvas
btn1 = tk.Button(cv, text="Click", command=next_image)
btn1.pack(side='left', padx=10, pady=5, anchor='sw')
root.mainloop()
... and here is the second script ...
# save as module secondscript.py
# display an image using Tkinter and PIL
# PIL allows Tkinter to read more than just .gif image files
import Tkinter as tk
from PIL import ImageTk
root = tk.Tk()
root.withdraw()
win = tk.Toplevel()
# size the window so the image will fit
win.geometry("%dx%d+200+100" % (360, 240))
# create all image objects in __main__ to be persistent
# pick an image file you have in your working directory
# or specify full path
image_file = "people2.bmp"
photo = ImageTk.PhotoImage(file=image_file)
win.title(image_file)
# put the image on a canvas
cv = tk.Canvas(win)
cv.pack(side='top', fill='both', expand='yes')
cv.create_image(0, 0, image=photo, anchor='nw')
if __name__ == '__main__':
win.mainloop()
In all fairness to snippsat, he did point out that DaniWeb contains a fair number of well commented PyQT examples to study and experiment with.
As of 08dec2009 we have:
Mainwindow frame ...
http://www.daniweb.com/forums/post864990.html#post864990
Boxlayout, button and canvas ...
http://www.daniweb.com/forums/post865059.html#post865059
Image display ...
http://www.daniweb.com/forums/post866067.html#post866067
Import, gridlayout, label and buttons ...
http://www.daniweb.com/forums/post866861.html#post866861
Geometry, title, listwidget ...
http://www.daniweb.com/forums/post867052.html#post867052
Painter, canvas, random circles ...
http://www.daniweb.com/forums/post867414.html#post867414
Painter, wallpaper background ...
http://www.daniweb.com/forums/post867456.html#post867456
Fontdialog ...
http://www.daniweb.com/forums/post867671.html#post867671
Movie widget and animated GIFs ...
http://www.daniweb.com/forums/post889575.html#post889575
Bar chart ...
http://www.daniweb.com/forums/post890195.html#post890195
Dial slider ...
http://www.daniweb.com/forums/post893284.html#post893284
Input dialogs ...
http://www.daniweb.com/forums/post922737.html#post922737
HTML code on label ...
http://www.daniweb.com/forums/post924074.html#post924074
Grid layout manager ...
http://www.daniweb.com/forums/post929766.html#post929766
Canvas draw ...
http://www.daniweb.com/forums/post929788.html#post929788
TableView ...
http://www.daniweb.com/forums/post931543.html#post931543
ListView ...
http://www.daniweb.com/forums/post932515.html#post932515
TableWidget ...
http://www.daniweb.com/forums/post933380.html#post933380
CalendarWidget ...
http://www.daniweb.com/forums/post938411.html#post938411
ListWidget ...
http://www.daniweb.com/forums/post939315.html#post939315
LineEdit with label ...
http://www.daniweb.com/forums/post940170.html#post940170
TextEdit ...
http://www.daniweb.com/forums/post940211.html#post940211
Progress bar and timer ...
http://www.daniweb.com/forums/post940222.html#post940222
Colorful canvas background ...
http://www.daniweb.com/forums/post940340.html#post940340
The almost IDE ...
http://www.daniweb.com/forums/post940472.html#post940472
Tooltip and colorful text ...
http://www.daniweb.com/forums/post947921.html#post947921
Canvas colorful radial gradient ...
http://www.daniweb.com/forums/post956030.html#post956030
ListWidget and newer programming styles ...
http://www.daniweb.com/forums/post979005.html#post979005
Tabular data …
I think Tom Gunn is an AI system that is down for the switch to Windows 7.
Not really, i just dont like moaners in general ;)
Do I detect a moan?
This simple code shows how to write text with a given font, font size and color using the module pygame ...
This code shows you how to create a drawing on a wxPython canvas and save the drawing to a standard image file ...
# use a drawing bitmap and wx.MemoryDC to create a canvas you can
# draw on and optionally save the drawing to an image file
# vegaseat
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(400, 150))
# create a bitmp for display and optional saving
self.show_bmp = wx.StaticBitmap(self)
# get the width and height for the blank bitmap
w, h = self.GetClientSize()
# create a blank bitmap as a drawing background
draw_bmp = wx.EmptyBitmap(w, h)
# put the canvas on top of draw_bmp
canvas = wx.MemoryDC(draw_bmp)
# fill the canvas white
canvas.SetBrush(wx.Brush('white'))
canvas.Clear()
# now draw something on the canvas ...
# set line colour and thickness (pixels)
canvas.SetPen(wx.Pen("blue", 15))
# DrawLine(x1, y1, x2, y2) from point (x1,y1) to (x2,y2)
canvas.DrawLine(50, 60, 340, 60)
# this also shows your drawing
self.show_bmp.SetBitmap(draw_bmp)
# optioally save the created image
# get the image object
myimage = self.show_bmp.GetBitmap()
myimage.SaveFile("myimage.jpg", wx.BITMAP_TYPE_JPEG)
app = wx.App(0)
MyFrame(None, 'draw a line using wx.MemoryDC').Show(True)
app.MainLoop()