A Tkinter Entry widget can be configured to "show" a character such as "".
[code]Tkinter.Entry(pwframe,width=25,show="
")[/code]

Excellent snippet vegaseat. The expanded event handler solves a common problem.

Here's another working example using the default argument trick:[code=Python]from Tkinter import *
from itertools import cycle

class SpinLabel(Frame):
def init(self, master=None):
Frame.init(self, master)
self.pack(fill=BOTH, expand=1)
self.master.title("Spin Characters")
self.textList = ["/", "--", "\", "--", "|"]
buttonFrame = Frame(self)
self.btnList = []
for i, name in enumerate(["Start", "Stop", "Exit"]):
btn = Button(buttonFrame, text=name, padx=5, pady=5,
bd=4, bg='#ff0', fg="#00f",
activebackground = "#00f",
activeforeground = "#ff0",
font=("Arial", 12, "bold"),
relief='raised')
btn.pack(side="left", fill=BOTH, expand=1)

        def handler(event, i=i):
            return self.manage_spin(i)
        btn.bind("<ButtonRelease-1>", handler)
        self.btnList.append(btn)
    buttonFrame.pack(fill=BOTH, expand=1)

    self.spin = Label(self, font=("Courier New", 24, 'bold'),fg='#000')
    self.spin.pack(side="top", fill=BOTH, expand=1)
    self.spinChrs = cycle(self.textList)

def manage_spin(self, idx):
    if idx == 0:
        self.btnList[0].configure(state=DISABLED)
        self.spinning = True
        self.loopchrs()
    elif idx == 1:
        self.btnList[0].configure(state=NORMAL)
        self.spinning = False
        self.spin.config(text="")
    elif idx == 2:
        self.master.destroy()

def loopchrs(self):
    if self.spinning:
        self.spin.config(text=self.spinChrs.next())
        self.spin.update_idletasks()
        self.spin.after(100, self.loopchrs)

if name == "main":
app = SpinLabel()
app.mainloop()[/code]

One more example:[code]import Tkinter
import random
"""Start with a grid of buttons with blank labels. When clicked, change the
text to a random number between 1 and 100."""

textFont3 = ("Arial", 12, "bold")

class App(Tkinter.Tk):
def init(self, cols, rows):
Tkinter.Tk.init(self)
self.title("Grid of Buttons")
self.cols = cols
self.rows = rows

    self.mainFrame = Tkinter.Frame(self)
    self.mainFrame.config(padx='3.0m', pady='3.0m')
    self.mainFrame.grid()
    # initialize button array
    self.buttonList = [[None for j in range(cols)] for i in range(rows)]
    self.create_buttons()

def create_buttons(self):
    for i in range(self.cols):
        for j in range(self.rows):
            btn = Tkinter.Button(self.mainFrame,text="",
                             anchor='center',
                             bd=3,
                             bg='#ffffff000',
                             fg="#000000fff",
                             activebackground = "#000000fff",
                             activeforeground = "#ffffff000",
                             font=textFont3,
                             padx='1.0m',
                             pady='1.0m',
                             relief='raised',
                             state='normal', width=6)
            self.buttonList[i].append(btn)

            btn.grid(row=j, column=i)
            def handler(event, ...

Create a Tkinter.Frame to hold the checker board and another frame to hold the buttons. Pack the frames "top". If you want the buttons along the bottom, pack "left". Add internal padding to each frame to get the desired space.

To eliminate duplication, initialize a list and iterate on columns and rows.[code] size = 50
cols = 8
rows = 8
squareList = []
for i in range(cols):
for j in range(rows):
if j%2: colors = ["black", "white"]
else: colors = ["white", "black"]
squareList.append(top.create_rectangle(isize, jsize,
isize+size, jsize+size,
fill=colors[i%2]))[/code]

Catch the EOFError with a try/except block.[code]dict = {}
print "Frequency list:"
while True:
try:
poem = raw_input()
except EOFError, e:
print "Reached the end of the file"
if poem == 'END':
break
for letter in poem:
if letter.isalpha():
if letter in dict:
dict[letter] = dict[letter] + 1
else:
dict[letter] = 1[/code]Why not read the file directly as in:[code]for letter in open(file_name).read():[/code]

To simplify the loop on [I]fileObj[/I]:[code]for line in fileObj:[/code]The for loop will terminate when a StopIteration is encountered which is typical for iterable objects.

You could use a combination of re and split. Find and remove all items in quotes first then split on space. Example:
[code]import re

s = '''10471 'AGHADA71' 20.00 2 0.00 0.00 1 1 1.0106 0.312 'AGGTREW 45'
10475 'AGHADA75' 21.00 2 0.00 0.00 1 1 0.9940 -1.217
10810 'AHANE 10' 110.00 1 0.00 'AHANE 10' 'AHANE 10' 0.00 1 1 1.0517 -4.091 '''

lines = s.split('\n')

patt = re.compile(r'\'(.+?)\'')
output = []
for line in lines:
lineList = []
while True:
m = patt.search(line)
if m:
lineList.append(m.group(1))
line = line[:m.start()] + line[m.end()+1:]
else:
break
lineList.extend([item.strip() for item in line.split() if item.strip()])
output.append(lineList)

for item in output:
print item[/code]I added additional quotes to test for a general solution. The output is:[code]>>> ['AGHADA71', 'AGGTREW 45', '10471', '20.00', '2', '0.00', '0.00', '1', '1', '1.0106', '0.312']
['AGHADA75', '10475', '21.00', '2', '0.00', '0.00', '1', '1', '0.9940', '-1.217']
['AHANE 10', 'AHANE 10', 'AHANE 10', '10810', '110.00', '1', '0.00', '0.00', '1', '1', '1.0517', '-4.091']

[/code]The drawback is the items are not in order.

voolvif,

You were not far off.[code]>>> pattern=re.compile(r"\%3D\%27([A-Z]+?)\%27\%3E",re.IGNORECASE)

pattern.findall(mystring)
['catherine', 'porter']
[/code]

d5e5 commented: Nice use of the lazy quantifier. +1

[QUOTE=Gribouillis;1022251]Does anyone know how I can test if an object's type is a builtin type or a user defined type ?[/QUOTE] If it's not builtin, it must be imported from another module.[code=Python]>>> getattr(list, 'module')
'builtin'

[/code]

Gribouillis commented: good idea +2

Use string method [I]strip()[/I] to remove newline characters.
[code=Python]for line in lines:
filemenu.add_cascade(label=line.strip())[/code]

Agni commented: thanks a lot.. +1

[I]obj[:3][/I] is a slice of the time.struct_time object. The asterisk preceding the list returned by the slice expands the list into individual elements. Example:[code=Python]>>> d = time.strptime('16/06/2010', '%d/%m/%Y')

d
(2010, 6, 16, 0, 0, 0, 2, 167, -1)
[d[0],d[1],d[2]]
[2010, 6, 16]
datetime.date(d[0],d[1],d[2])
datetime.date(2010, 6, 16)
datetime.date(*d[:3])
datetime.date(2010, 6, 16)
d[:3]
(2010, 6, 16)
[/code]The DeprecationWarning you are seeing is unrelated to the code we are discussing, but originates in the pyXLWriter module. Warnings can be suppressed or turned into exceptions with a call to [I]filterwarnings()[/I], which adds an entry to the warning filter. See Python documentation.

iamthwee commented: Thanks again +17

I thought my use of [U][I]enumerate()[/I][/U] would give you enough information. Here's the code again with code to write to the Excel file (untested):[code=Python]print "\nLooping through the file, line by line."
workbook = xl.Writer("simple.xls")
worksheet = workbook.add_worksheet()
f = open("omg.txt", "r")
for i, line in enumerate(f):
for j, obj in enumerate([convertType(item) for item in
[w.strip() for w in line.strip().split('\t')]
]):
worksheet.write([i, j], obj)

workbook.close()
f.close()
[/code]

iamthwee commented: Almost there +17

Decide what types of objects that need to be converted. If needed, create a function to make each conversion type. An exception should occur on any failed conversion. If all conversions fail, return a string. Example:
[code=Python]import time

def fdim(s):

return a float given a fraction (EX. '1/2')
ss = s.split('/')
return float(ss[0])/float(ss[1])

def evalList(s):

return a list given a string representation
if s.strip().startswith('[' ) and s.strip().endswith(']'):
    try: return eval(s)
    except: raise ValueError
raise ValueError

def evalDateStr(s):

return a struct_time object given a string representation
return time.strptime(s, '%m/%d/%Y')

def convertType(s):
for func in (int, float, evalDateStr, fdim, evalList):
try:
n = func(s)
return n
except:
pass
return s

s = "6 \t 1.02 \t hello \t 01/02/2008 \t [1,2,3] \t 15/16"

for obj in [convertType(item) for item in [w.strip() for w in s.split('\t')]]:
print '%s - object type: %s' % (obj, type(obj))[/code]Output:
[code=Python]>>> 6 - object type: <type 'int'>
1.02 - object type: <type 'float'>
hello - object type: <type 'str'>
(2008, 1, 2, 0, 0, 0, 2, 2, -1) - object type: <type 'time.struct_time'>
[1, 2, 3] - object type: <type 'list'>
0.9375 - object type: <type 'float'>

[/code]

iamthwee commented: awesome +17

It appears that you omitted an operator:
yIntercept = y1 - (((y2 - y1)/(x2 - x1))[B][COLOR="Red"](add operator here)[/COLOR]/B)

vegaseat commented: sharp eye, nice +8

[code]>>> s = 'XXXXX -\n\t XXXX'

''.join(s.split())
'XXXXX-XXXX'
[/code]

Ene Uran commented: nice solution! +4

Try this:
[code=Python]csv.reader(str(self[filename]).split('\n')[/code]The argument to csv.reader can be any iterable object that produces a string each time its [I]next()[/I] method is called.

vegaseat commented: Nice solution +8

[quote=aot;328810]Here's something that I've wished for a number of times so far: the ability to create a function (taking X) that creates X variables, even if they are all initialized to the same value. For example, [inlinecode]f(3)[/inlinecode] would assign [inlinecode]var1 = 0[/inlinecode], [inlinecode]var2 = 0[/inlinecode], and [inlinecode]var3 = 0[/inlinecode].

My program runs an experiment, and I'd love for the number of sections to be a variable that I could change at will (so I could expand it later if I wanted). Each section requires a certain number of variables for keeping track of things like how many problems the participant solved correctly. So you can see how useful the above would be to me...

Anyway, I assume it can't be done. But are there other ways to deal with my problem? I'd love to find out.[/quote] If I understand you correctly, there are several ways:

Update the local namespace

for i in range(25):
... exec "%s = %d" % ('var'+str(i), 0) in None

Update the global namespace

dd = {}
for i in range(25):
... dd['var'+str(i)] = 0
globals.update(dd)

Update the local namespace with dictionary dd

for key in dd:
... exec "%s = %s" % (key, repr(dd[key])) in None
...

Update a module namespace with dd

import P3D
P3D.dict.update(dd)

var0
0
var1
0
var24
0