Is the RAM used as the buffer?
I would say yes, unless your Operating System uses disk space as virtual memory.
Is the RAM used as the buffer?
I would say yes, unless your Operating System uses disk space as virtual memory.
One rude awakening with Python3 will be the frequent use of bytearrays instead of strings. It does this to handle international unicode better.
Here is how you deal with this:
# get code of given URL as html text string
# Python3 uses urllib.request.urlopen()
# instead of Python2's urllib.urlopen() or urllib2.urlopen()
import urllib.request
fp = urllib.request.urlopen("http://www.python.org")
mybytes = fp.read()
# note that Python3 does not read the html code as string
# but as html code bytearray, convert to string with
mystr = mybytes.decode("utf8")
fp.close()
print(mystr)
Also the online book "dive into python" has been mostly
rewritten for Python3 (check appendix A for 2to3 diffs):
http://diveintopython3.org/
Swaroop C.H. has rewritten his excellent beginning Python tutorial for Python3:
http://www.swaroopch.com/notes/Python_en:Table_of_Contents
There is example at:
http://www.daniweb.com/forums/showpost.php?p=947978&postcount=46
that might work.
What happens if you run this test code:
#!/usr/bin/env python
# example frame.py
# http://www.pygtk.org/pygtk2tutorial/sec-Frames.html
import pygtk
pygtk.require('2.0')
import gtk
class FrameExample:
def __init__(self):
# create new window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Frame Example")
# connect "destroy" event to signal handler
window.connect("destroy", lambda w: gtk.main_quit())
window.set_size_request(300, 300)
# set border width of window
window.set_border_width(10)
# create the Frame
frame = gtk.Frame()
window.add(frame)
# set the frame's label
frame.set_label("GTK Frame Widget")
# align the label at the right of the frame
frame.set_label_align(1.0, 0.0)
# set the style of the frame
frame.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
frame.show()
# display the window
window.show()
def main():
# enter the event loop
gtk.main()
return 0
if __name__ == "__main__":
FrameExample()
main()
Do you get error message?
What is your Operating System?
Which version of Python?
Which version of PyGTK?
On Windows PyGTK is almost impossible to install!
I like wxPython. However, if you use the newer Python 3.1, it could take long time for wxPython to be available. So now I am learning PyQT.
Again, Tkinter isn't bad to learn in the beginning, just to get used to GUI programming concepts. To me PyGT is really complex, try to make listbox display and you see.
Function raw_input() would force the user to type in the entire XML code. I don't think you want this.
Normally the XML code would come from file, something like this:
fin = open("Myxml.xml", "r")
xml_string = fin.read()
fin.close()
# now the xml code is represented by xml_string for you to work on.
For now, I am working on:
s=raw_input("Enter a number to simplify: ") global p p=0 def loop(): for i in s: p+=int(i) if(p>9): loop() return p print(p)
You got the right idea, but if you insist on recursion, you have to follow certain rules:
#s=raw_input("Enter a number to simplify: ")
s = '123456789' # for test
def loop(s, p=0):
for i in s:
p += int(i)
if p > 9:
# recursively loop with adjusted string s
return loop(str(p))
return p
n = loop(s)
print(n) # 9
You can give your wxPython window nice custom icon:
# experiment with wxPython's wx.Icon() and SetIcon()
import wx
class MyFrame(wx.Frame):
"""make a frame, inherits wx.Frame"""
def __init__(self):
wx.Frame.__init__(self, None, -1, 'wxPython custom icon',
pos=wx.Point(300, 150), size=wx.Size(300, 350))
self.SetBackgroundColour('green')
# pick icon file (.ico) you have ...
#iconFile = "py.ico"
# or 32x32 Windows .bmp file will do ...
# (will miss mask if not rectangular image)
icon_file = "Attention32x32.bmp"
self.SetIcon(wx.Icon(icon_file, wx.BITMAP_TYPE_ICO))
# show the frame
self.Show(True)
application = wx.App(0)
# call class MyFrame
window = MyFrame()
application.MainLoop()
You can use 32x32 Windows .bmp file instead of .ico file.
Hint, in while loop turn the number string into list of individual digits and sum the list until the sum is less than 10, then break.
Careful here, you are using strings(characters) and integers. So you have to use str() and int() to convert at the appropriate time.
For example:
s = '123'
print list(s) # ['1', '2', '3']
# for sum() you want list of integers
print [int(x) for x in s] # [1, 2, 3]
print sum([int(x) for x in s]) # 6
Example of wx.ScrolledWindow to display large area in one small frame:
# test wx.ScrolledWindow(parent, id, pos, size, style)
# with multiple widgets that exceed normal frame area
# tested with Python 2.5.4 and wxPython 2.8.9.1
# Henri
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, mytitle):
wx.Frame.__init__(self, parent, -1, mytitle, size=(400,300))
# create scrolled window
# let the wx.ScrolledWindow fill the frame
self.scrollw = wx.ScrolledWindow(self, wx.ID_ANY)
self.scrollw.SetBackgroundColour('green')
# set EnableScrolling(bool x_scrolling, bool y_scrolling)
# default is self.scrollw.EnableScrolling(True, True)
# if True, wx.ScrolledWindow shows its scroll bars
# create the scroll bars, set the scrolling ranges (pixels)
max_w = 1000
max_h = 1000
# SetScrollbars(pixelsPerUnitX, pixelsPerUnitY, noUnitsX,
# noUnitsY)
self.scrollw.SetScrollbars(20, 20, max_w//20, max_h//20)
# pick something that needs area larger than the frame
self.createMultiLabels()
def createMultiLabels(self):
"""from one of vegaseat's example codes"""
# things to put on the labels
label_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ->UM'
# wx.GridSizer(rows, cols, vgap, hgap)
gsizer = wx.GridSizer(6, 5, 0, 0)
# create list of labels
# acccess with self.labels[0], self.labels[1] etc.
self.labels = []
for c in label_string:
# labels have of scroll window as parent
self.labels.append(wx.StaticText(self.scrollw, -1,
label=c, style=wx.ALIGN_CENTRE|wx.SUNKEN_BORDER))
# iterate through the list of labels and set
# layout, optionally font and colour
font = wx.Font(60, wx.MODERN, wx.NORMAL, wx.BOLD)
for x in self.labels:
x.SetFont(font)
x.SetBackgroundColour("yellow")
gsizer.Add(x, 0, flag=wx.ALL, border=20)
# set the sizer in scroll window
self.scrollw.SetSizer(gsizer)
app = wx.App(0)
# create MyFrame instance and show the frame
MyFrame(None, "wx.ScrolledWindow for large display").Show()
app.MainLoop()
Now I see, you want to avoid flood of email from DaniWeb.
You can:
1 Follow jlm699 advice
2 Try your Python skills and write small program to UNsubscribe you. :)
The wxPython wx.lib.fancytext.StaticFancyText() class can display colorful text written in XML format:
# wxPython's
# wx.lib.fancytext.StaticFancyText(parent, id, text, ...)
# can display text written in XML format
# Henri
import wx
import wx.lib.fancytext as wxft
class FancyText(wx.Panel):
def __init__(self, parent, xml_text):
wx.Panel.__init__(self, parent, -1)
self.ftext = wxft.StaticFancyText(self, -1, text=xml_text,
background=wx.Brush('black'))
red = '<font family="swiss" color="red" size="48">'
blue = '<font family="swiss" color="blue" size="48">'
green = '<font family="swiss" color="green" size="48">'
# match the 3 <font ...> tags with closing </font> tags
xml_text = """\
%s Feeling %sblue?
%s Or green with envy?
</font>
</font>
</font>
""" % (red, blue, green)
app = wx.App(0)
mytitle = 'wx.lib.fancytext.StaticFancyText()'
mysize = (620, 220)
frame = wx.Frame(None, -1, title=mytitle, size=mysize)
FancyText(frame, xml_text)
frame.Show()
app.MainLoop()
The Open Graphics Library (OGL) is now well integrated with wxPython, but to go from there to something that works like VPython you need lots of work:
import wx
import wx.lib.ogl as ogl
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__( self, None, wx.ID_ANY,
title="explore wx.lib.ogl", size=(400,300))
canvas = ogl.ShapeCanvas(self)
canvas.SetBackgroundColour("yellow")
diagram = ogl.Diagram()
# marry the two ...
canvas.SetDiagram(diagram)
diagram.SetCanvas(canvas)
# create some standard shapes ...
# (check how creation order affects overlap)
circle = ogl.CircleShape(100.0) # radius
circle.SetX(75.0) # center x
circle.SetY(75.0)
circle.SetPen(wx.RED_PEN)
circle.SetBrush(wx.CYAN_BRUSH)
canvas.AddShape(circle)
text = ogl.TextShape(250, 30) # (w, h)
text.SetX(180) # center x
text.SetY(240)
text.AddText("you can drag the circle or the text")
canvas.AddShape(text)
diagram.ShowAll(True)
# use v box sizer
sizer = wx.BoxSizer(wx.VERTICAL)
# canvas will grow as frame is stretched
sizer.Add(canvas, 1, wx.GROW)
self.SetSizer(sizer)
app = wx.App()
ogl.OGLInitialize()
MyFrame().Show()
app.MainLoop()
I have Python2.5.4 and Python3.1 working on the same XP machine.
Programming editors (IDE) like IDLE may have to be convinced with batch file to use the correct Python version.
Here is example:
REM batch file to force IDLE to run with Python 3.1
REM save as IDLE31.bat
C:\Python31\Pythonw.exe -u C:\Python31\Lib\idlelib\idle.pyw
One similar batch file needs to be created for Python25.
Only potential problem with place() is, that it does not resize with window.
The Tkinter GUI toolkit has data input dialogs that will validate your input, as shown here:
# Python GUI toolkit Tkinter has three different data input dialogs:
# tkSimpleDialog.askstring(title, prompt [,options])
# tkSimpleDialog.askinteger(title, prompt [,options])
# tkSimpleDialog.askfloat(title, prompt [,options])
# does error trapping with int and float, also optional max/min
# there is also an initialvalue=parameter
try:
# for Python2
import Tkinter as tk
import tkSimpleDialog as tksd
except:
# for Python3
import tkinter as tk
import tkinter.simpledialog as tksd
root = tk.Tk()
# parent=root needed to put dialog window on top of parent root window
mystr = tksd.askstring("Dialog (String)", "Enter your name:", parent=root)
print(mystr)
age = tksd.askinteger("Dialog (Integer)", "Enter your age:", parent=root,
minvalue=0, maxvalue=120)
print(age)
pay = tksd.askfloat("Dialog (Float)", "Enter your annual pay:",
parent=root, minvalue=1000)
print(pay)
root.mainloop()
# optional help
#help(tksd)
Yes, instead of using geometry manager pack() or grid(), use place(x, y) for layouts. Note that place(x, y) is absolute, and coordinates x or y can go negative to shift the widget out off the window. One nice trick!
Care should be taken not to mix the different geometry managers!!!
You can use this:
mylist = [
[1, 9, 22, 28, 0.69887889000000003, 0.98993399999999998, 2],
[4, 27, 6, 22, 0.81186093999999998, 1.1221458099999999, 2],
[4, 27, 100, 30, 0.74796748000000002, 1.0448537600000001, 2],
[4, 1, 30, 45, 0.48522300000000002, 0.77061900999999999, 2],
[4, 27, 1, 51, 0.54467741999999997, 0.83013524999999999, 2],
[4, 28, 22, 4, 0.77556899999999995, 1.0917697900000001, 2],
[5, 27, 22, 50, 0.81594683999999995, 1.1273952, 2],
[6, 27, 22, 31, 0.91040723999999995, 1.26681591, 2],
[7, 108, 22, 53, 0.69060584999999997, 0.98095147999999999,2],
[8, 27, 22, 46, 0.94473684000000002, 1.33349425, 2]]
# inplace sort by the 4th item which is at index 3
ix = 3
mylist.sort(key=lambda x: x[ix])
for item in mylist:
print(item)
""" result =
[4, 28, 22, 4, 0.775569, 1.09176979, 2]
[4, 27, 6, 22, 0.81186094, 1.12214581, 2]
[1, 9, 22, 28, 0.69887889, 0.989934, 2]
[4, 27, 100, 30, 0.74796748, 1.04485376, 2]
[6, 27, 22, 31, 0.91040724, 1.26681591, 2]
[4, 1, 30, 45, 0.485223, 0.77061901, 2]
[8, 27, 22, 46, 0.94473684, 1.33349425, 2]
[5, 27, 22, 50, 0.81594684, 1.1273952, 2]
[4, 27, 1, 51, 0.54467742, 0.83013525, 2]
[7, 108, 22, 53, 0.69060585, 0.98095148, 2]
"""
Pick your project and use C++ to write your code. There will be the time that is rather obvious when you want to switch to Python.
This perhaps shows how you can do this:
http://www.daniweb.com/forums/showpost.php?p=714874&postcount=100
How do I use wx.Gauge to show the progress of very slow process?
# show the progress of slow process with wx.Gauge widget
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, mytitle, mysize):
wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
panel = wx.Panel(self)
# for instance process takes total seconds
total = 50
# range set to 0 to total
self.gauge1 = wx.Gauge(panel, wx.ID_ANY, range=total,
pos=(10, 10), size=(390, 15), style=wx.GA_HORIZONTAL)
self.val = 1
self.timer = wx.Timer(self)
interval = 1000 # (in milliseconds)
self.timer.Start(interval)
# bind EVT_TIMER event and
# update the gauge every interval
self.Bind(wx.EVT_TIMER, self.update_gauge)
# code your process here ...
def update_gauge(self, event):
"""move the gauge one notch"""
self.gauge1.SetValue(self.val)
self.val += 1
app = wx.App(0)
# create one MyFrame instance and then show the frame
MyFrame(None, 'use wx.Gauge to show progress', (420, 300)).Show()
app.MainLoop()
There are variety of cursors available using the wx.StockCursor() in wxPython:
# a look at cursors and wx.StockCursor()
import wx
class MyFrame(wx.Frame):
"""create a color frame, inherits from wx.Frame"""
def __init__(self, parent):
wx.Frame.__init__(self, parent, wx.ID_ANY, "Left click the mouse",
size=(500, 300))
self.SetBackgroundColour('yellow')
self.count = 0
# just to show you how to set it, actually the default cursor
self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
# bind mouse left click event
self.Bind(wx.EVT_LEFT_DOWN, self.onLeftDown)
def onLeftDown(self, event):
"""left mouse button is pressed"""
# get (x, y) position tuple
pt = event.GetPosition()
# put cursor globals in as strings so the name can be shown
cursors = ['wx.CURSOR_SPRAYCAN', 'wx.CURSOR_NO_ENTRY', 'wx.CURSOR_BULLSEYE',
'wx.CURSOR_CROSS', 'wx.CURSOR_HAND', 'wx.CURSOR_IBEAM',
'wx.CURSOR_MAGNIFIER', 'wx.CURSOR_PENCIL', 'wx.CURSOR_RIGHT_ARROW',
'wx.CURSOR_QUESTION_ARROW', 'wx.CURSOR_WAIT', 'wx.CURSOR_ARROWWAIT',
'wx.CURSOR_PAINT_BRUSH', 'wx.CURSOR_SIZING']
s = "cursor = %s at point %s" % (cursors[self.count], str(pt))
self.SetTitle(s)
# use eval() to get the integer value back
int_val = eval(cursors[self.count])
self.SetCursor(wx.StockCursor(int_val))
self.count += 1
if self.count >= len(cursors):
self.count = 0
app = wx.App(0)
MyFrame(None).Show()
app.MainLoop()
Sometimes you want to change the colour of the widget as the mouse pointer moves over it. Here is the wx.Button() code example:
# change the color of the button as the mouse pointer moves over it
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(300, 100))
# panel needed to size the single button properly
panel = wx.Panel(self, wx.ID_ANY)
self.button = wx.Button(panel, wx.ID_ANY,
'move the mouse pointer over the button',
pos=(10, 10), size=(-1, -1))
self.button.SetBackgroundColour('green')
# bind mouse events to actions
self.button.Bind(wx.EVT_ENTER_WINDOW, self.mouse_over)
self.button.Bind(wx.EVT_LEAVE_WINDOW, self.mouse_not_over)
self.button.Bind(wx.EVT_BUTTON, self.button_clicked)
def mouse_over(self, event):
self.button.SetBackgroundColour( 'yellow')
#self.button.Refresh()
def mouse_not_over(self, event):
self.button.SetBackgroundColour( 'green')
#self.button.Refresh()
def button_clicked(self, event):
self.SetTitle("button has been clicked")
app = wx.App(0)
MyFrame(None, 'show mouse-over event').Show()
app.MainLoop()
There is usually info in the MS-HTML-Help file
wx.chm
if wxPython does not have one particular feature.
Also look at:
http://wiki.wxpython.org/index.cgi/FrontPage
This is the API ref, very extensive:
http://prdownloads.sourceforge.net/wxpython/wxPython-newdocs-2.8.8.1.tar.bz2
Seems to me like a nice technique. It is steganography, right?
As far as I understand, steganography would be to change each byte of image file just one small amount, so the picture essentially looks the same. Comparing it with the original picture would reveal the secret message hidden in the small changes.
So, I guess I can assume that md5 is not reversible, right?
That is the idea, and the reason md5 is used for encrypting the password itself. Encryption of the text itself can be donw with a number of Python tools. Very simple one would be XOR encryption against the looped password. I think there is code snippet under Python for that. Check out:
http://www.daniweb.com/code/snippet688.html
Something like this will do:
for line in wordlistfile:
wordlist.append(line.strip())
Simply use this:
# list all the modules Python currently knows about ...
help("modules")
At first blush i would say this might do:
# compare these two list set and convert
# w_b into [0.5, 0, 0.5, 0]
a = ['a', 'b', 'c', 'd']
w_a = [0.25, 0.25, 0.25, 0.25]
b = ['a', 'c']
w_b = [0.5, 0.5]
for ix, aa in enumerate(a):
if aa not in b:
w_b.insert(ix, 0)
print w_b # result --> [0.5, 0, 0.5, 0]
Also note that you can combine two related lists in one container:
# combine two lists to show their relationship better
a = ['a', 'b', 'c', 'd']
w_a = [0.25, 0.25, 0.25, 0.25]
# list of (name, weight) tuples
print zip(a, w_a) # [('a', 0.25), ('b', 0.25), ('c', 0.25), ('d', 0.25)]
# dictioary with name:weight pairs
print dict(zip(a, w_a)) # {'a': 0.25, 'c': 0.25, 'b': 0.25, 'd': 0.25}
BTW, dictionaries are much faster way to look things up then indexing two separate related lists:
a = ['a', 'b', 'c', 'd']
w_a = [0.25, 0.25, 0.25, 0.25]
b = ['a', 'c']
w_b = [0.5, 0.5]
dict_a = dict(zip(a, w_a))
dict_b = dict(zip(b, w_b))
for k, v in dict_a.items():
if k not in dict_b.keys():
dict_b[k] = 0
print dict_b # {'a': 0.5, 'c': 0.5, 'b': 0, 'd': 0}
Proof that [::-1] works for spelling string in reverse:
s1 = "racecar"
s2 = "kayak"
print s1, s1[::-1]
print s2, s2[::-1]
:)
Functions sort() and sorted() reside in the core of the Python interpreter which is written in C and compiled. On Windows the Python core is for instance in the dynamic link library called python25.dll which the Python installer put into directory C:\WINDOWS\system32
Here is example of the rather slow but classic bubble sort for integer list:
import random
def make_list(num_elements):
"""
make list of num_elements random integers between 0 and 1000
"""
return [random.randint(0, 1000) for i in xrange(num_elements)]
def bubble_sort(list1):
# make true copy of list1 so there is no feedback
list1 = list(list1)
for i in xrange(len(list1) - 1, 0, -1):
for j in xrange(1, i + 1):
if list1[j - 1] > list1[j]:
temp = list1[j - 1]
list1[j - 1] = list1[j]
list1[j] = temp
return list1
list2 = make_list(100)
print list2 # unsorted
print "-"*70
list3 = bubble_sort(list2)
print list3 # now sorted
Hope that helps.
The wx.lib.filebrowsebutton.FileBrowseButton() makes it easy to select/browse one file and show or play it:
# exploring wxPython's
# wx.lib.filebrowsebutton.FileBrowseButton()
# use it to get wave sound file and play it
import wx
import wx.lib.filebrowsebutton
class MyFrame(wx.Frame):
def __init__(self, parent, mytitle):
wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=(500,100))
self.SetBackgroundColour("green")
panel = wx.Panel(self)
self.fbb = wx.lib.filebrowsebutton.FileBrowseButton(panel,
labelText="Selected WAVE file:", fileMask="*.wav")
play_button = wx.Button(panel, wx.ID_ANY, ">> Play")
self.Bind(wx.EVT_BUTTON, self.onPlay, play_button)
# setup the layout with sizers
hsizer = wx.BoxSizer(wx.HORIZONTAL)
hsizer.Add(self.fbb, 1, wx.ALIGN_CENTER_VERTICAL)
hsizer.Add(play_button, 0, wx.ALIGN_CENTER_VERTICAL)
# create border space
border = wx.BoxSizer(wx.VERTICAL)
border.Add(hsizer, 0, wx.EXPAND|wx.ALL, 15)
panel.SetSizer(border)
def onPlay(self, evt):
filename = self.fbb.GetValue()
self.sound = wx.Sound(filename)
# error handling ...
if self.sound.IsOk():
self.sound.Play(wx.SOUND_ASYNC)
else:
wx.MessageBox("Missing or invalid sound file", "Error")
app = wx.App(True)
# create the MyFrame instance and show the frame
caption = "wx.lib.filebrowsebutton.FileBrowseButton()"
MyFrame(None, caption).Show(True)
app.MainLoop()
Shows you how to drag one of wxPython's widgets with the mouse pointer:
# use mouse to drag the wx.Panel() widget
# wx.Panel(parent, id, pos, size, style)
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, mytitle, mysize):
wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
# needed for better control
panel = wx.Panel(self)
panel.SetBackgroundColour("green")
self.drag_panel = wx.Panel(panel, size=(230, 100))
self.drag_panel.SetBackgroundColour("yellow")
text1 = "point the mouse on the yellow panel \n"
text2 = "press the left mouse button and drag it"
wx.StaticText(panel, wx.ID_ANY,
text1+text2, pos=(10, 150))
# bind mouse events to some actions
self.drag_panel.Bind(wx.EVT_LEFT_DOWN, self.on_left_down)
self.drag_panel.Bind(wx.EVT_LEFT_UP, self.on_left_up)
self.drag_panel.Bind(wx.EVT_MOTION, self.on_motion)
def on_left_down(self, event):
self.drag_panel.CaptureMouse()
x, y = self.drag_panel.ClientToScreen(event.GetPosition())
originx, originy = self.drag_panel.GetPosition()
dx = x - originx
dy = y - originy
self.mp_delta = ((dx, dy))
def on_left_up(self, event):
if self.drag_panel.HasCapture():
self.drag_panel.ReleaseMouse()
def on_motion(self, event):
if event.Dragging() and event.LeftIsDown():
x, y = self.drag_panel.ClientToScreen(event.GetPosition())
move_xy = (x - self.mp_delta[0], y - self.mp_delta[1])
self.drag_panel.Move(move_xy)
app = wx.App()
# create the MyFrame instance and show the frame
MyFrame(None, 'drag the panel with the mouse', (400, 300)).Show()
app.MainLoop()
The Pope is the closest human to God.
Once k gets past the number of available elements in your list you will get an IndexError. You can put in series of if statements making sure that k does not exceed the length of your list, or simply trap the error to break out of the while loop:
list2 = [23, 764, 12, 54, 83, 2, 543, 890, 1235, 453, 98]
width = 5 # experiment with this value
k = 0
while True:
try:
print str(list2[k]).ljust(width),
k = k + 1
print str(list2[k]).ljust(width),
k = k + 1
print str(list2[k]).ljust(width),
k = k + 1
except IndexError:
break
print
last = list2[-1]
Sneekula left one small starter editor somewhere around DaniWeb. So I took it and modified it to use the wxPython toolbar with icon images rather than Snee's menu bar. The images come from wxPython's builtin art library:
# the start of one small text editor with toolbar and image icons
# notice that the wx.TextCtrl() surface has already some advanced
# features: select text, right click to cut, copy and paste etc.
import os
import wx
class MyFrame(wx.Frame):
def __init__(self, title):
wx.Frame.__init__(self, None, wx.ID_ANY, title, size=(500, 300))
self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)
# statusBar at the bottom of the window
self.CreateStatusBar()
self.SetStatusText(" Click on the icon")
# ToolBar at the top of the window
toolbar = wx.ToolBar(self, -1, style=wx.TB_HORIZONTAL|wx.NO_BORDER)
toolbar.SetToolBitmapSize(size=(24,24))
toolbar.AddSimpleTool(wx.ID_OPEN, self.getBMP(wx.ART_FILE_OPEN),
"Load", " Load a text file")
toolbar.AddSimpleTool(wx.ID_SAVE, self.getBMP(wx.ART_FILE_SAVE),
"Save", " Save the text file")
toolbar.AddSimpleTool(wx.ID_ABOUT, self.getBMP(wx.ART_INFORMATION),
"About"," About message")
toolbar.AddSeparator()
toolbar.AddSimpleTool(wx.ID_EXIT, self.getBMP(wx.ART_QUIT),
"Exit"," Exit the program")
toolbar.Realize()
self.SetToolBar(toolbar)
# bind the various toolbar icon click events to some action
self.Bind(wx.EVT_TOOL, self.onLoad, id=wx.ID_OPEN)
self.Bind(wx.EVT_TOOL, self.onSave, id=wx.ID_SAVE)
self.Bind(wx.EVT_TOOL, self.onAbout, id=wx.ID_ABOUT)
self.Bind(wx.EVT_TOOL, self.onExit, id=wx.ID_EXIT)
def getBMP(self, pic_id):
"""get the bitmap image from the wxPython art provider"""
return wx.ArtProvider.GetBitmap(pic_id, wx.ART_TOOLBAR, wx.Size(24, 24))
def onAbout(self, e):
""" the about box """
about = wx.MessageDialog( self, " A very simple text editor \n"
" using the wxPython GUI toolkit", "About Simple Editor", wx.OK)
about.ShowModal()
about.Destroy()
def onLoad(self, e):
""" open text file"""
self.dirname = ''
mask = "Text (.txt)|*.txt|All (.*)|*.*"
dlg = wx.FileDialog(self, "Choose a file to load",
self.dirname, "", mask, wx.OPEN)
if …
Well, if you do web-page designing, you will be familiar with the repeating image tile wallpaper. You can do something similar to give your wxPython frame or panel very sexy backgrounds. I leaned on one of vegaseat's snippets to come up with this example:
# wallpaper wxPython panel using one image as repeating tile
# (image is obtained from base 64 encoded png image string)
import wx
import cStringIO
import base64
class MyPanel(wx.Panel):
"""
class creates panel for the tile image contained in data_stream
"""
def __init__(self, parent, id, frame_w, frame_h, data_stream):
# create the panel
wx.Panel.__init__(self, parent, id)
# frame/panel width and height
self.frame_w = frame_w
self.frame_h = frame_h
# convert to bitmap
self.bmp = wx.BitmapFromImage(wx.ImageFromStream(data_stream))
# do the wall papering on the PaintDC canvas...
wx.EVT_PAINT(self, self.on_paint)
# now put some widgets on top of the panel's wallpaper
self.button1 = wx.Button(self, -1, label='Button1', pos=(15, 10))
self.button2 = wx.Button(self, -1, label='Button2', pos=(15, 45))
def on_paint(self, event=None):
# create the paint canvas
dc = wx.PaintDC(self)
dc.Clear()
# get image width and height
image_w = self.bmp.GetWidth()
image_h = self.bmp.GetHeight()
# use repeating image tiles to wallpaper the canvas
for x in range(0, self.frame_w, image_w):
for y in range(0, self.frame_h, image_h):
dc.DrawBitmap(self.bmp, x, y, True)
# the base64 encoded png image string
png_b64='''\
iVBORw0KGgoAAAANSUhEUgAAAGQAAABkBAMAAACCzIhnAAAAMFBMVEUEAgQEAoYEAkgEAsYEAicE
AqgEAmkEAucEAhgEApgEAlkEAtYEAjgEArkEAnsEAvxjNQuZAAAFBUlEQVR4nNWXT2gcVRjAv91O
l+kyjd02kSSFYY21CtpUGIKHMGTBFkIpgVAeMpFtNlZi20MEc5jDHrKtRXOQ4LYGHA/rKuhBNB4W
CXQM2QY9GEWEdSgxPLsvhNBoO6Gp6dI/OH5vN7U97XsDXvwOe3o/vj/z5pvfQsDjHoC2UoTm0d0O
Px+4sP8lqCN3EdkrQpRk/GrNDoJHyBdJAQLJM1f54UfI5ykBoabUrqcfR2LdoiQYGmw8RG4hclYC
UWHXQ2QiBVOvSyA4g+Ft5OtfYCEphUCkgdzf8QCuyxEAz9eRy3FLLcoB/bk3OXI/p1jxnBQReyMb
wN8f47wUS7YsPrG/duENU3+XRaKI3IHDD0A5KYtAXwD3YNcmKAVpZCdHIndBGZRG4Bosws4tUPLy
iAar8OMQKE/KIwBVGGmF+I0wSA4u7IGWqjwQ5T97IJILk6UeB0IT/79QDp79VOpgLoersdeseGsn
iGclxcAAmeBvaq02u2yYnjX9vpD4LGjErDteqqQ9kv9QiJAGUatlXaPiEcv5QKKw+Tpju6USTRMn
v1eMQPQaX4azbsmkHnEKKxIIf7+Del003TGoy2TB7RbU7Oy4QQlxOhJy74U2UbN5Em+JJArtUghs
2Fm316RpyymwVTlkN9aF3VtOXtd9OeTIMk9CrOk8W2Pl5mcvHDl+cHRthLUtG5UKIdY6W2XN+59h
jfD1cyV8KFYizzLdfzRFcsd8fl5PsLhpEJLHVsrvjOWaVzaA5y8ZprOPUs+ZdhgrxkTNKL6+v0Rd
1zCXPGeQsZlUfKbYHME0jK3PlswKdayOgv4CaGsiBMawtOWSQa02PuKihKlAC07sxBylQ5F8gnVi
qXszzYGFL/nE/jQqZEjFuvCZaKuCj7WawOfNPjFMMgTnEqwVkfY9grpG/MwVVk5TRLCtKiLXRcgU
q6oMzhHyEcAVfo219qoAUf3rMJCCm/Sb0cVX7G95LyIE4hn1VE9jlwXBHYmJYSRPbZ/fdruVpBAp
K6PDjyNig1RBPa/NbyNbuG+EBslDgbe3kVuSBokRnfi3sNhrcgi83EDmkzAgZ5DYUV8dOfwiHChL
Io1ubu9+S9YgY22J+sx+jRIlKZljB1/+wW1QnGhOEokFweZGKIMEZT54EAs2w+ggPIvG+W4ogwQF
kUgogwQ4ehkiW2F6weiCHSidehikHb66CFpnCELNwMxqOIPUkEKDzIQpDCMDkZAExnPhkf80lP7J
EKfXRs8eP4Nyl5IFxsDmX3jPskS7Gmfe1UYIma9B1p0zqIzc1Z2LixpkswbP4gjt5uE2tGHcNWja
cfIXRcjk/oZB2mCbRg/KXUJC7r6vJ8lCCY0o7VgFGbk72iis1Gv2YCtMSiGHsS4XXEqnl5y8nNy1
BDYW5lbQu5w8k1uKfXYWezHpkoVGJPf6PWFnS1Cpe5eus5QMos26Lsw16lrxTwtOq+8tLCyOXsIs
tIeQjnU9M9J0ysfGfJ/roK4fcoGml3iW5MBYM+SnGb0ejCkGmEvTToL5mdhYuWldnOlwHHaIArXw
tugj5bhfbIpEdf3mRNY2zAp4noOeehA0kQ8+pbcl1rlBQsNTUe46BYjm+/q6W5qjMPSDc1LvzEn4
4BR28+pchcJvmqPz/yjKjeav8mR/Nw55n2l6MATdut4q1q7zdUm/iX9qEIkyVuVyJ7jLjJ0eYd/h
JQZpubvCqnE99Uya/APf6sMx1/lYCAAAAABJRU5ErkJggg==
'''
# convert to png image bytes
png_bytes = base64.b64decode(png_b64)
# convert png bytes …
Nice stuff there Fuse and Ene!
Here is my contribution, showing you how easy it is to have wxPython display an image from image file:
# show .jpg .png .bmp or .gif image on wx.Panel
import wx
class ImagePanel(wx.Panel):
""" create the panel and put image on it """
def __init__(self, parent, id):
# create the panel, this will be self
wx.Panel.__init__(self, parent, id)
try:
# pick your image file you have in the working folder
# or use the full file path
image_file = 'strawberry.jpg'
bmp = wx.Bitmap(image_file)
# show the bitmap, image's upper left corner anchors
# at panel coordinates (5, 5), default is center
wx.StaticBitmap(self, -1, bmp, (5, 5))
# show some image information
info = "%s %dx%d" % (image_file, bmp.GetWidth(), bmp.GetHeight())
# the parent is the frame
parent.SetTitle(info)
except IOError:
print "Image file %s not found" % imageFile
raise SystemExit
# redirect=False sends stdout/stderr to the console window
# redirect=True sends stdout/stderr to a wx popup window (default)
app = wx.App(redirect=False)
# create window/frame, no parent, -1 is the default ID
# also increase the size of the frame for larger images
frame = wx.Frame(None, -1, size = (480, 320))
# create the panel instance
imp = ImagePanel(frame, -1)
# show the frame
frame.Show(True)
# start the GUI event loop
app.MainLoop()
I think the Pythonic approach is the use of powerful, optimized modules. So yeah, wxPython uses powerful, optimized widgets.
Python has clearly borrowed the best of several earlier languages.
It is only a duck if it acts, looks and sounds like one. Processed duck is not a duck.
Change
while [(t1.arm==0) or (t2.arm==0)]:
to
while (t1.arm > 0) or (t2.arm > 0):
Write your major algorithms and test them thoroughly.
Now design the GUI and bring in the algorithms. If you are familiar with QT use PyQt, otherwise you better start with the more popular wxPython GUI toolkit. You can get drag and drop frame builder for wxPython called Boa Constructor.
Using wxPython makes distribution of your finshed program easier and has no licensing requirements like QT.
I am using SPE, it's okay, it incorporates wxGlade (GUI builder) and the excellent WinPdb (debugger), but it does not have some features like code completion.
I use mostly PyScripter, it is written with Delphi, and has the features I want. It's a standalone .exe file that works on Windows.
There is free download from:
http://pyscripter.googlepages.com/
Actually, I like to use SPE for debugging and PyScripter for experimenting with Python code.
Never used Eric so far, might check it out.
Here is example how you could approach this project:
# exploring recursion
def average(qq=[]):
"""
using empty list as default will make the list static
recursion forms its own loop, break out with return
"""
try:
x = float(raw_input("Enter number (q to quit): "))
qq.append(x)
print "data list =", qq
avg = sum(qq)/len(qq)
print "average =", avg
# the function calls itself (recursion)
average()
except:
# actually anything but number will quit
print 'quit'
return
average()
Not perfect, but start.
You need to get involved in parsing, here is example:
data = '''\
"returns=int",
"operationName=doComplexStuff",
var1="integer",
var2="(a="integer", b="integer")",
var3="(a="string", b="integer")"
'''
q = data.split(',')
m = []
t = ""
con = False
for k in range(len(q)):
s = q[k].strip()
# parse for () pairs and concatenate
# before appending (set con flag)
if '(' in s:
con = True
if con == True and ')' not in s:
t += s + ','
if ')' in s:
t += s
m.append(t)
t = ""
con = False
elif con == False:
m.append(s)
# show result
for w in m:
print w
"""
my result -->
"returns=int"
"operationName=doComplexStuff"
var1="integer"
var2="(a="integer",b="integer")"
var3="(a="string",b="integer")"
"""
There are parsing modules available for Python.
Ya its amazing how useless penicillin is becoming with the resistance of pathogenic bacteria growing. They will soon run out anti-bacterial chemicals produced by fungi and humans and then were screwed.
That when phages will come back into the limelight.
Mutating bacteria and prokaryotes could eventually become the ultimate undefeated enemy.