Try something like this ...
new_line = [1.2, 2.4, 1234.5]
line_jn = ' '.join(['%15E' % x for x in new_line])
print(line_jn) # 1.200000E+00 2.400000E+00 1.234500E+03
Try something like this ...
new_line = [1.2, 2.4, 1234.5]
line_jn = ' '.join(['%15E' % x for x in new_line])
print(line_jn) # 1.200000E+00 2.400000E+00 1.234500E+03
Just a quick look at the PyQT QListWidget list box ...
# a simple window using PyQT
# with a button and a listbox to load and select
# tested with Python 3.1.1 and PyQT 4.71
# vegaseat
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MyForm(QWidget):
def __init__(self, name_list):
QWidget.__init__(self)
# setGeometry(x_pos, y_pos, width, height)
self.setGeometry(100, 150, 300, 220)
self.setWindowTitle("Load the listbox first")
# make name_list available for methods
self.name_list = name_list
# use a grid layout for the widgets
grid = QGridLayout()
btn_load = QPushButton("Load List")
# bind the button click to a function reference
# new connect style, needs PyQt 4.5+
btn_load.clicked.connect(self.on_click)
self.listbox = QListWidget()
# new connect style, needs PyQt 4.5+
self.listbox.clicked.connect(self.on_select)
# addWidget(widget, row, column, rowSpan, columnSpan)
grid.addWidget(btn_load, 0, 0, 1, 1)
# listbox spans over 5 rows and 2 columns
grid.addWidget(self.listbox, 1, 0, 5, 2)
self.setLayout(grid)
def on_click(self):
"""the load button has been clicked, load the listbox"""
self.listbox.addItems(self.name_list)
self.setWindowTitle("Select a name ...")
def on_select(self):
"""an item in the listbox has been clicked/selected"""
#selected_name = self.listbox.selectedItems()[0].text()
selected_name = self.listbox.currentItem().text()
self.setWindowTitle(selected_name)
name_list = [
"Erich Meitinger",
"Udo Baus",
"Jens Klein",
"Bjorn Bork",
"Heidrun Lovelace",
"Klaus Abraham",
"Ulla Jorgens",
"Volger Jenkings",
"Helmut Schmidt",
"Freja Larse",
"Larry Orkan",
"Andreas Mauser",
"Harry Heimlich"
]
app = QApplication([])
form = MyForm(name_list)
form.show()
app.exec_()
This little code allows you you to use the mouse wheel on Tkinter with either Windows or Linux ...
# explore the mouse wheel with Tkinter
try:
# Python2
import Tkinter as tk
except ImportError:
# Python3
import tkinter as tk
class MyApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title("mouse wheel action")
# use width x height + x_offset + y_offset (no spaces!)
self.geometry("300x120+50+50")
self['bg'] = 'dark green'
self.counter = 0
# Windows
self.bind("<MouseWheel>", self.mouse_wheel)
# Linux
self.bind("<Button-4>", self.mouse_wheel)
self.bind("<Button-5>", self.mouse_wheel)
self.label = tk.Label(self, font=('courier', 16, 'bold'),
width=10)
self.label.pack(padx=20, pady=40)
def mouse_wheel(self, event):
"""respond to Linux or Windows wheel event"""
if event.num == 5 or event.delta == -120:
self.counter -= 1
if event.num == 4 or event.delta == 120:
self.counter += 1
self.label['text'] = self.counter
app = MyApp()
app.mainloop()
You can download the graphics.py module from:
http://mcsp.wartburg.edu/zelle/python/graphics.py
The module itself has some demo/test code in it. There is also a reference to Prof. Zelle's book that uses this module.
Here is a typical example ...
# draw a circle on top of two rectangles
# using module graphics from:
# http://mcsp.wartburg.edu/zelle/python/graphics.py
from graphics import *
# create the window/frame
w = 300
h = 300
win = GraphWin("Red Circle", w, h)
# first rectangle using corner x, y coordinates
upper_left = Point(0, 0)
lower_right = Point(300, 150)
rect1 = Rectangle(upper_left, lower_right)
rect1.setFill('yellow')
rect1.setWidth(0) # no border
rect1.draw(win)
# second rectangle using corner x, y coordinates
upper_left = Point(0, 150)
lower_right = Point(300, 300)
rect2 = Rectangle(upper_left, lower_right)
rect2.setFill('green')
rect2.setWidth(0) # no border
rect2.draw(win)
# circle needs center x, y coordinates and radius
center = Point(150, 150)
radius = 80
circle = Circle(center, radius)
circle.setFill('red')
circle.setWidth(2)
circle.draw(win)
# wait, click mouse to go on/exit
win.getMouse()
win.close()
Experiment with the coordinates and colors a little.
This might be a good example you can customize to your needs:
http://www.daniweb.com/forums/post1154551.html#post1154551
Just an experiment with box sizers and panels to get a desired layout ...
# use a wx.BoxSizer() for multisizer widget layout
# wx.VERTICAL = stacked vertically
# wx.HORIZONTAL = stacked horizontally
# add widget with Add() --> has options ...
# proportion=0 no vertical stretch with frame stretch in sizer_v
# proportion=1 stretch with frame stretch
# proportion=2 fill remaining space proportional (eg. 1:2)
# proportion=3 fill remaining space proportional (eg. 1:3)
# border=n use a n pixel wide border
# wx.ALL puts the specified border on all sides
# (also has wx.LEFT wx.RIGHT wx.TOP and wx.BOTTOM)
# flag=wx.EXPAND --> expand to fit frame
# flag=wx.SHAPED --> change size preserving original aspect ratio
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, mytitle, mysize):
wx.Frame.__init__(self, parent, -1, mytitle, size=mysize)
panel1 = wx.Panel(self, -1, style=wx.SUNKEN_BORDER)
panel2 = wx.Panel(self, -1, style=wx.SUNKEN_BORDER)
panel3 = wx.Panel(self, -1, style=wx.SUNKEN_BORDER)
panel1.SetBackgroundColour("blue")
panel2.SetBackgroundColour("red")
panel3.SetBackgroundColour("green")
# use two different BoxSizer() to layout the controls
# in this case the vertical sizer will be the main sizer
sizer_v = wx.BoxSizer(wx.VERTICAL)
sizer_h = wx.BoxSizer(wx.HORIZONTAL)
# add widgets to horizontal sizer
# proportions are set to fill space ratio 1:2
# keeps ratio on frame stretch
sizer_h.Add(panel1, proportion=1, flag=wx.EXPAND)
sizer_h.Add(panel2, proportion=2, flag=wx.EXPAND)
# now add to vertical sizer in order
sizer_v.Add(panel3, proportion=1, flag=wx.EXPAND)
sizer_v.Add(sizer_h, proportion=3, flag=wx.EXPAND)
# set the main sizer only
self.SetSizer(sizer_v)
app = wx.App(0)
# create a MyFrame instance and show the frame
MyFrame(None, "Multi BoxSizer() Test", (300, 250)).Show()
app.MainLoop()
The secret of a happy marriage remains a secret.
-- Henny Youngman
Give light, and the darkness will disappear of itself.
-- Desiderius Erasmus
I put my heart and my soul into my work, and have lost my mind in the process.
-- Vincent van Gogh
Finding the ideal spot for a vacation means a lot of 'googling.'
You missed the obvious option, jwenting. Open the skull, put black ink over the cortex, stamp it on a sheet of paper. Voila, brain fingerprinting.
That wouldn't be brain fingerprinting that would be brain cortexprinting. You got to get a finger in there somewhere. :)
Well, thank you for the many contributions to the Python forum. Those were well done posts!
...
I just noticed 2 wasn't shown. Maybe I don't have it....
A little simpler, and you might just have it ...
s = """
2
6
18
22
"""
s = s.split()
i = 1
while i <= 26:
if str(i) in s:
print "gotcha"
else:
print str(i)
i += 1
A little playful ...
s = "knockknock"
s2 = s.replace("knock", "bam", 1)
print s2
s3 = s.replace("knock", "bam")
print s3
s4 = s3.replace("bam", "knock", 1)
print s4
# combine s3 and s4 action
s5 = s.replace("knock", "bam").replace("bam", "knock", 1)
print s5
""" my result -->
bamknock
bambam
knockbam
knockbam
"""
Well i always like to prefer USA whether they win or lose. They are my all time favorite.
I assume you are selling a t-shirt about that topic.
A classy example of the Tkinter GUI toolkit. It shows you how to draw a circle on a canvas and move it around using the arrow keys ...
# use a Tkinter canvas to draw a circle, move it with the arrow keys
# vegaseat
try:
# Python2
import Tkinter as tk
except ImportError:
# Python3
import tkinter as tk
class MyApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title("move circle with arrow keys")
# create a canvas to draw on
self.cv = tk.Canvas(self, width=400, height=400, bg='white')
self.cv.grid()
# create a square box with upper left corner (x,y)
self.x = 120
self.y = 120
size = 150
box = (self.x, self.y, self.x + size, self.y + size)
# create a circle that fits the box
self.circle = self.cv.create_oval(box, fill='red')
# bind arrow keys to movement
self.bind('<Up>', self.move_up)
self.bind('<Down>', self.move_down)
self.bind('<Left>', self.move_left)
self.bind('<Right>', self.move_right)
def move_up(self, event):
# move_increment is 5 pixels
y = -5
# move circle by increments x, y
self.cv.move(self.circle, 0, y)
def move_down(self, event):
y = 5
self.cv.move(self.circle, 0, y)
def move_left(self, event):
x = -5
self.cv.move(self.circle, x, 0)
def move_right(self, event):
x = 5
self.cv.move(self.circle, x, 0)
app = MyApp()
app.mainloop()
This shows you how to create a keypad with Tkinter. The code uses a for-loop to reduce the amount of typing ...
# create a calculator key pad with Tkinter
# tested with Python 3.1.1 and Python 2.5.4
# vegaseat
try:
# Python2
import Tkinter as tk
except ImportError:
# Python3
import tkinter as tk
# needs Python25 or higher
from functools import partial
def click(btn):
# test the button command click
s = "Button %s clicked" % btn
root.title(s)
root = tk.Tk()
root['bg'] = 'green'
# create a labeled frame for the keypad buttons
# relief='groove' and labelanchor='nw' are default
lf = tk.LabelFrame(root, text=" keypad ", bd=3)
lf.pack(padx=15, pady=10)
# typical calculator button layout
btn_list = [
'7', '8', '9', '*', 'C',
'4', '5', '6', '/', 'M->',
'1', '2', '3', '-', '->M',
'0', '.', '=', '+', 'neg' ]
# create and position all buttons with a for-loop
# r, c used for row, column grid values
r = 1
c = 0
n = 0
# list(range()) needed for Python3
btn = list(range(len(btn_list)))
for label in btn_list:
# partial takes care of function and argument
cmd = partial(click, label)
# create the button
btn[n] = tk.Button(lf, text=label, width=5, command=cmd)
# position the button
btn[n].grid(row=r, column=c)
# increment button index
n += 1
# update row/column position
c += 1
if c > 4:
c = 0
r += 1
root.mainloop()
All in all a great start for a calculator program.
You can create a list of lists this way ...
# assume that raw data is read/obtained as a string
data_str = """\
d.complex.1
24
25
67
123
764
d.complex.2
23
54
35
64
d.complex.3
1
2
3
"""
data_list = []
# split at the 'd' char, later put 'd' back in
for data in data_str.split('d'):
# exclude empty data
if data:
temp_list = []
# split at the newline char
for item in data.split('\n'):
# exclude any empty item
if item:
if item.startswith('.'):
# put the 'd' back in
item = 'd' + item
temp_list.append(item)
data_list.append(temp_list)
print( data_list )
"""my prettied up result -->
[
['d.complex.1', '24', '25', '67', '123', '764'],
['d.complex.2', '23', '54', '35', '64'],
['d.complex.3', '1', '2', '3']
]
"""
You can use Python modules math, wave, and struct to create and save a synthetic sine wave of given frequency and duration (size) ...
Since hex numbers '87' and 'c4' are not even in your charset, it could take you a very long time to match. :)
You could use this little test program ...
import random
# search for this upper case HexValue string:
# use hex digit pairs that are in the charset
value = "%X" % 0x2e1077
print value # test upper case hex
# Character Set:
charset = [
'01', '02', '03', '04', '05', '06', '07', '08', '09', '0b', '0c',
'0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18',
'19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23',
'24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e',
'30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3b',
'3c', '3d', '3e', '41', '42', '43', '44', '45', '46', '47', '48',
'49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53',
'54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e',
'5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69',
'6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74',
'75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f']
n = 0
while True:
ran1 = random.sample(charset, 3)
str1 = ''.join(ran1).upper()
#print(str1) # test
if str1 == value:
break
n += 1
print("It took %d samples to find %s" % (n, value))
With 4 * 2 hex digits this brute force approach can take a long time, so I sampled only 3 pairs.
If you are interested in reading particular lines from a data file, look at module linecache.
I would approach it this way ...
def is_magic(n):
"""check if n is a perfect (magic) number"""
acc = 0
for i in range(1, n):
if (n % i == 0):
factor = i # these 2 lines could be acc += i
acc += factor
if (acc == n):
return True
else:
return False
def print_magic(limit):
"""print all the perfect numbers up to limit"""
for i in range(1, limit):
if is_magic(i):
print( i )
# test function ismagic
n = 28
print is_magic(n)
# test function print_magic
# this is a brute force approach and takes
# quite a bit of time with larger limits
# (wait till you are done)
print( "wait ..." )
print_magic(10000)
print( "... done!" )
You got to let Python know where you want to create the Tkinter widgets. By default it's the MainWindow root. Change your code like this ...
from Tkinter import *
class TopLevel3:
def __init__(self):
self.root2 = Toplevel()
# lift root2 over MainWindow root1
self.root2.lift(aboveThis=mw.root1)
self.canvas3 = Canvas(self.root2, width=400, height=200)
self.canvas3.pack()
# easier parent name
cv = self.canvas3
self.root2.title("ImageDB")
r = 0
for c in range(6):
# make canavas the parent here
Label(cv, relief=RIDGE, width=55).grid(row=r, column=0)
Entry(cv, relief=SUNKEN, width=20).grid(row=r, column=1)
Button(cv, text='View Image').grid(row=r, column=2)
Button(cv, text='Update Tag').grid(row=r, column=3)
r = r+1
self.root2.mainloop()
class MainWindow:
"""class for testing"""
def __init__(self):
self.root1 = Tk()
self.root1.title("MainWindow")
def img_db(self):
TopLevel3()
mw = MainWindow()
mw.img_db()
Again, I would import with a namespace.
That particular software is very early alpha at best.
At this point it is very clumsy and will frustrate you thoroughly!
This little code might give you a hint ...
# print out the third Fridays of each month in a given year
import calendar
year = 2010
print( "The third Friday of each month in %d:" % year )
for month in range(1, 13):
k = 0
for day in range(1, 32):
try:
weekday = calendar.weekday( year, month, day)
except ValueError:
continue
if weekday == calendar.FRIDAY:
k += 1
if k == 3:
# format the result
print( "%02d/%02d/%d" % (month, day, year) )
I don't have BOA, but I quickly created a sample program using the wxGlade designer and the SPE editor. It shows you how to set up a tree ...
#!/usr/bin/env python
# -*- coding: iso-8859-15 -*-
# generated by wxGlade 0.6.2 on Fri Feb 19 05:43:46 2010
import wx
# begin wxGlade: extracode
# end wxGlade
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrame.__init__
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.tree = wx.TreeCtrl(self, -1)
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_TREE_SEL_CHANGED, self.selected, self.tree)
# end wxGlade
self.mystuff()
def mystuff(self):
# --- the following code is added by the programmer --->
# you can only have one root
root = self.tree.AddRoot("Computer")
# these form subroots
os = self.tree.AppendItem(root, 'Systems')
tk = self.tree.AppendItem(root, 'Toolkits')
# add 3 items to subroot os
os_items = ["Windows", "Solaris", "Linux"]
for item in os_items:
self.tree.AppendItem(os, item)
# add 3 items to subroot tk
tk_items = ["Tkinter", "wxPython", "Qt"]
for item in tk_items:
self.tree.AppendItem(tk, item)
# start with root expanded to show subroots
self.tree.Expand(root)
def __set_properties(self):
# begin wxGlade: MyFrame.__set_properties
self.SetTitle("frame")
self.SetSize((400, 300))
# end wxGlade
def __do_layout(self):
# begin wxGlade: MyFrame.__do_layout
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.tree, 1, wx.EXPAND, 0)
self.SetSizer(sizer)
self.Layout()
# end wxGlade
def selected(self, event): # wxGlade: MyFrame.<event_handler>
# --- the following code is added by the programmer --->
item_text = self.tree.GetItemText(event.GetItem())
sf = "selection changed: %s" %item_text
self.SetTitle(sf)
# end of class MyFrame
if __name__ == "__main__":
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame = MyFrame(None, -1, "")
app.SetTopWindow(frame)
frame.Show()
app.MainLoop()
Note:
For Python26 I am …
You have a choice of import statements. Using no namepace is simple to type, but if you import several modules you lose track of where the object came from. Also, if modules have the same named object you will get conflicts.
# import without namespace
from Tkinter import *
root = Tk()
s = "Hello World!"
label = Label(root, text=s, bg='yellow', fg='red')
label.pack(side='left', padx=20, pady=20)
root.mainloop()
This import uses the full module name as namespace and may be a little too much typing. Notice how the namespace is prefixed to the object.
# import with full namespace
import Tkinter
root = Tkinter.Tk()
s = "Hello World!"
label = Tkinter.Label(root, text=s, bg='yellow', fg='red')
label.pack(side='left', padx=20, pady=20)
root.mainloop()
A compromise is to use an abbreviation of the module name, for Tkinter the abbreviation tk is very common.
# import with abbreviated namespace
# pick a recognizable somewhat unique abbreviation
import Tkinter as tk
root = tk.Tk()
s = "Hello World!"
label = tk.Label(root, text=s, bg='yellow', fg='red')
label.pack(side='left', padx=20, pady=20)
root.mainloop()
As a side note, the Python2 module Tkinter.py has become a package named tkinter in Python3. This modified import statement would allow you run your Tkinter code in both versions of Python with a namespace.
# import with abbreviated namespace
# can be used with Python2 and Python3 versions
try:
# Python2
import Tkinter as tk
except ImportError:
# Python3
import tkinter as tk
root = tk.Tk()
s = "Hello World!"
label = tk.Label(root, text=s, bg='yellow', …
A true conservationist knows that the world is not given by the fathers, but borrowed from the children.
-- John James Audubon
Here is an odd one, you be the judge ...
America is the most grandiose experiment the world has seen, but, I am afraid, it is not going to be a success.
-- Sigmund Freud
Probably uttered during Sigmund's final years, when the first Great Depression was in full swing in the US.
Your problem is with
self.image= ImageTk.PhotoImage(Image.open(filename))
in this case self.image has already been converted to a Tinter image which does not have method resize()
You need to create the PIL image with
img = Image.open(filename)
do your resize on that with
img_resized = img.resize(width*scale, height*scale, Image.ANTIALIAS)
and then convert to a Tkinter image with
self.image = ImageTk.PhotoImage(image=img_resized)
before you can show it with Tkinter.
Your previous issue was the use of self to pass an object to a class method. Look as this simple example ...
class MyClass:
def __init__(self):
self.text = "text from MyClass method show_text"
self.show_text()
def show_text(self):
print(self.text)
# create an instance of MyClass
mc = MyClass()
The namespace issue might come up if you are using import statements like this
from Tkinter import *
that is for careless folks.
Just for the fun of Python ...
# using the Python local dictionary vars()
# you can dump/save and load mystr_dict with module pickle
def mystrings():
s1 = 'I '
s2 = 'like '
s3 = 'Python'
# in this case vars() is local to this function
return vars()
mystr_dict = mystrings()
print(mystr_dict) # {'s3': 'Python', 's2': 'like', 's1': 'I'}
# add mystr_dict to vars() local to __main__
vars = vars().update(mystr_dict)
print(s1+s2+s3) # I like Python
Google for "Bing"
There are quite a number of errors in your code. Check the remarks ending with '!!!!!!!!!!!' in the corrected code ...
import random
class Card:
def __init__(self, suit, rank, value):
self.rank = rank
self.suit = suit
self.value= value
if self.rank == 1:
self.rank = "Ace"
self.value = 11
elif self.rank == 11:
self.rank = "Jack"
self.value = 10
elif self.rank == 12:
self.rank = "Queen"
self.value = 10
elif self.rank == 13:
self.rank = "King"
self.value = 10
elif 2 <= self.rank <= 10:
self.value = self.rank # this line first!!!!!!!!!
self.rank = str(self.rank)
if self.suit == 1:
self.suit = "Clubs"
if self.suit == 2:
self.suit = "Spades"
if self.suit == 3:
self.suit = "Diamonds"
if self.suit == 4:
self.suit = "Hearts"
self.cardname = self.rank + " of " + self.suit
deck = []
for suit in range(1,5):
for rank in range(1,14):
for value in range(2,12):
deck.append(Card(suit,rank,value))
class Player:
def player_turn(self):
# prefix hand with 'self.' to pass into method !!!!!!
self.hand = []
for cards in range(0,2):
a = random.choice(deck)
self.hand.append(a)
deck.remove(a)
print "This is your hand:"
for card in self.hand:
print card.cardname
print "Would you like to hit or stay?"
response = raw_input("'hit' or 'stay' (h or s) ").lower()
while 'h' in response:
card=random.choice(deck)
self.hand.append(card)
deck.remove(card)
print "Your next card is", card.cardname
ptotal=0
for i in self.hand:
ptotal = int(i.value) + ptotal
if ptotal > 21:
break
print "Would you like to hit or stay?"
response = raw_input("'hit' or 'stay' (h or s) ").lower()
return ptotal
def …
If you work with the wxPython option, you can only save the C++ code and an xml file at this point. You have to copy and paste the Python code directly to your Python editor, add a "driver" to the bottom and flesh out the code to your needs.
Here is a typical code example mostly produced by the wxFormBuilder program ...
###########################################################################
## Python code generated with wxFormBuilder (version Jun 11 2009)
## http://www.wxformbuilder.org/
##
## PLEASE DO "NOT" EDIT THIS FILE!
###########################################################################
import wx
###########################################################################
## Class MyFrame2
###########################################################################
class MyFrame2 ( wx.Frame ):
def __init__( self, parent ):
wx.Frame.__init__ ( self, parent, id = wx.ID_ANY,
title = u"T Calculator", pos = wx.DefaultPosition,
size = wx.Size( 335,220 ),
style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
self.SetBackgroundColour( wx.Colour( 0, 128, 0 ) )
bSizer4 = wx.BoxSizer( wx.VERTICAL )
bSizer4.AddSpacer( ( 0, 0 ) )
self.label1 = wx.StaticText( self, wx.ID_ANY,
u" Enter a temperature value below: ",
wx.DefaultPosition, wx.DefaultSize, 0 )
self.label1.Wrap( -1 )
self.label1.SetBackgroundColour( wx.Colour( 255, 255, 128 ) );
bSizer4.Add( self.label1, 0, wx.ALL, 5 )
self.m_textCtrl1 = wx.TextCtrl( self, wx.ID_ANY,
wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer4.Add( self.m_textCtrl1, 0, wx.ALL, 5 )
self.m_button1 = wx.Button( self, wx.ID_ANY,
u"Calculate Temperature", wx.DefaultPosition,
wx.DefaultSize, 0 )
self.m_button1.SetMinSize( wx.Size( 210,-1 ) );
bSizer4.Add( self.m_button1, 0, wx.ALL, 5 )
self.m_textCtrl2 = wx.TextCtrl( self, wx.ID_ANY,
wx.EmptyString, wx.DefaultPosition, wx.DefaultSize,
wx.TE_MULTILINE )
self.m_textCtrl2.SetMinSize( wx.Size( 310,-1 ) );
bSizer4.Add( self.m_textCtrl2, 0, wx.ALL, 5 )
bSizer4.AddSpacer( ( 0, 0 ) )
self.SetSizer( bSizer4 ) …
I let you in on a secret, don't tell anybody else, I love to eat out in relatively close by Las Vegas.
I wish all the Indians out there a very Happy 61st Republic Day! :-)
A fantastic achievement! Congratulations!
The USA will celebrate its 234th (or is it the 235th) Independence Day on July 4th. It took quite a bid of bloodshed and many years to kick the British overlords out then.
"You get what you pay for."
-- unknown wise guy
Don't you just hate it when...
people smear their signature spam all over.
My old boss used to have a password so difficult to remember that he had to write it on a label on his keyboard.:)
Since we don't have your data file, we can simply create a sample test file and use that to show you how you can extract the numeric data after the marker ...
# create a test data string
raw_data = """\
a
b
c
DATA
11
22
17.5
45
19.5
66.5
"""
# write the test data file
fname = "mydata.txt"
fout = open(fname, "w")
fout.write(raw_data)
fout.close()
# read the test data file line by line and create a list
# of all the numeric items after the DATA marker
data_list = []
data_flag = False
for line in open(fname):
line = line.rstrip()
if data_flag == True:
data_list.append(float(line))
if line == "DATA":
data_flag = True
# test print the result ...
print(data_list) # [11.0, 22.0, 17.5, 45.0, 19.5, 66.5]
Now you can access the numbers in your data_list by index, or sequentially to process them.
To create a simple spell checker you can search a given word list. Here is a simple example ...
# find a search word in a list of words using a linear search
#
# DictionaryE.txt has about 110,000 lower case English words
# one word per line
# download DictionaryE.zip from ...
# http://www.daniweb.com/forums/post160495.html#post160495
# load the dictionary file
fname = "DictionaryE.txt"
word_list = []
for line in open(fname):
# strip trailing whitespace like newline char
word_list.append(line.rstrip())
# test
#print(word_list[:10])
# pick a search word
search = "spinach"
try:
# do a standard linear search
index1 = word_list.index(search)
print( "Found word %s at index %d" % (search, index1) )
except ValueError:
print( "Did not find word %s in the word list!" % search )
If you had to search for a larger number of words, then this code will be much faster ...
# find a search word in a list of words using a binary search
# for long lists a binary search is faster than a linear search
#
# DictionaryE.txt has about 110,000 lower case English words
# one word per line
# download DictionaryE.zip from ...
# http://www.daniweb.com/forums/post160495.html#post160495
import bisect
# load the dictionary file
fname = "DictionaryE.txt"
word_list = []
for line in open(fname):
# strip trailing whitespace like newline char
word_list.append(line.rstrip())
# test
#print(word_list[:10])
# binary searches require a sorted list
word_list.sort()
# pick a search word
search = "spinach"
# note bisect.bisect() is the same as …
Put a little milk in my Kahlua, tastes real good!
Don't you wish there was a knob on the TV to turn up the intelligence of the program? There's one marked 'Brightness,' but it doesn't work.
-- Gallagher
"God helps those who help themselves"
-- Benjamin Franklin
To access a dictionary key use print Card.VALUES["1"]
Also in your case there is no key named "1"
Just about anybody can learn to play the piano, but very few can be a concert pianist. To be good at playing the piano takes real talent and a special mind. The same goes for programmers.
To hire a good one you have to hear them play, or in this case give a coding performance.
Darn double post again, sorry!
Nice Ironpython code Lardmeister, thanks!
If you don't want the frills (color, button) you can really simplify the code using defaults ...
# add '99 bottles of beer' lyrics to a .NET list box
# simplified code using some defaults
# tested with IronPython 2.6 by vegaseat
import clr
clr.AddReference('System.Windows.Forms')
import System
from System.Windows.Forms import *
from System.Collections import ArrayList
class BeerSong(Form):
def __init__(self):
self.Text = '99 Bottles of Beer'
# create the listbox and fill the form (self) with it
box = ListBox()
box.Dock = DockStyle.Fill
self.Controls.Add(box)
# move the lyrics into ArrayList then transfer to the box
array = ArrayList()
bottle = "%s bottle"
beer = "s of beer on the wall!"
take = "Take one down, pass it around,"
for k in range(99, 0, -1):
# an exercise in slicing
s1 = bottle % k + beer[k==1:]
s2 = (bottle % k + beer[k==1:])[:-13] + "!"
s3 = bottle % (k-1 or "No")
s4 = beer[k==2:-1] + "!"
array.Add(s1)
array.Add(s2)
array.Add(take)
array.Add(s3+s4)
array.Add(" ")
box.DataSource = array
Application.Run(BeerSong())
According to some recent pop-up ads, Bill Gates lives in terror worrying about online software created by this advertiser. :)
The only blemish I can see with wxPython is that it will not work with Python3 at the moment.
PyQT works with Python3, but may have licensing problems down the road.
Tkinter is pretty much cross platform and comes with Python2 and Python3. Its widgets are rather basic and look a little homely on a Windows machine, but look great on Apple's OS.
Ironpython 2.6 is a close equivalent of Python 2.6 with the added advantage of having access to CLR and the MS .NET Framework. It can use the Framework's library as a GUI toolkit. For a good example see:
http://www.daniweb.com/forums/post1104553.html#post1104553