Ene Uran 638 Posting Virtuoso

Don't forget that an ace can be 1 or 11

Ene Uran 638 Posting Virtuoso

So, you want to do a Google search from your Python program, here is the code:

# search Google
 
import webbrowser
 
search_str = raw_input("Enter Google search string: ")
 
# convert to a list and process
qlist = search_str.split(None)
list1 = []
for q in qlist:
    if '+' in q:
        q = q.replace('+', '%2B')
    if ' ' in q:
        q = '"%s"' % q
    q = q.replace(' ', '+')
    list1.append(q)
 
# convert back to a string
query = '+'.join(list1)
url = "http://www.google.com/search?q=%s" % query
 
webbrowser.open(url)
Ene Uran 638 Posting Virtuoso

Always check you statement blocks! After you program with Python for a short while, these kind of things stick out like a sore thumb.

Ene Uran 638 Posting Virtuoso

You most likely get the error because you haven't selected anything on the listbox yet. You need to bind the listbox to the mouseclick that does the selection and to a function that contains your get(index) code. Something like this:

from Tkinter import *

musicfolder = [
  ["CollegeRock/"],
  ['RnB/'],
  ['HipHop/'],
  ['Build/'],
  ['Buy/'],
  ['Techno/'],
  ['Jazz/'],
  ['Classic/']
]

def get_list(event):
    """
    function to read the listbox selection
    and put the result in an entry widget
    """
    # get selected line index
    index = listbox1.curselection()[0]
    # get the line's text
    seltext = listbox1.get(index)
    # delete previous text in enter1
    enter1.delete(0, 50)
    # now display the selected text
    enter1.insert(0, seltext)
    
root = Tk()

# create the listbox (note that size is in characters)
listbox1 = Listbox(root, width=50, height=6)
listbox1.grid(row=0, column=0)

# create a vertical scrollbar to the right of the listbox
yscroll = Scrollbar(command=listbox1.yview, orient=VERTICAL)
yscroll.grid(row=0, column=1, sticky=N+S)
listbox1.configure(yscrollcommand=yscroll.set)

# create data entry
enter1 = Entry(root, width=50, bg='yellow')
enter1.insert(0, 'Click on an item in the listbox')
enter1.grid(row=1, column=0)

# load the listbox with data
for item in musicfolder:
    listbox1.insert(END, item)
 
# left mouse click on a list item to display selection
listbox1.bind('<ButtonRelease-1>', get_list)

root.mainloop()
Ene Uran 638 Posting Virtuoso

You should have 2 files, let's say your p2e templet file p2e_test1.py modified with your code filename, and your code file test1.py. Save these 2 files in the same directory and just douple-click on p2e_test1.py

That's really all there is to it!

Otherwise make sure the Python versions match, you seem to be using Python 2.5. I avoid IDLE as an IDE, just too primitive!

Ene Uran 638 Posting Virtuoso

hello friend, i am a new programmer, i have probem use gotoxy in visual c++, help me please :cheesy:

Hmm, another Turbo C hold-over! You can replace it with the SetPixel() function from the Windows GDI32.lib. Vegaseat had plowed those fields long ago, and there is an example he left in the code snippets. Old C++ code, but should still work:

// plot a sinewave to the console window (cmd window)
// link with GDI32.lib or using Dev-C++ link libgdi32.a via
// Project>>Project Options>>Parameters>>Add Lib>>libgdi32.a
// this is a Windows Console Application   vegaseat  06mar2005
 
#include <cstdio>
#include <cmath>
#include <windows.h>
 
int main(void)
{
  int x, y;
  COLORREF yellow = RGB(255,255,0);
  COLORREF lightblue = RGB(173,216,230);
  
  // make sure the names match
  SetConsoleTitle("ConGraphics");
  HWND hWnd = FindWindow(NULL, "ConGraphics");
 
  HDC hDC = GetDC(hWnd);
  
  // draw a yellow sine curve
  for(x = 0; x < 700; x++)
  {
    // center at y = 200 pixels
    y = (int)(sin(x/100.0)*100 + 200);
    SetPixel(hDC, x, y, yellow);
  }
    
  // draw center line
  for(x = 0; x < 700; x++)
  {
    SetPixel(hDC, x, 200, lightblue);
  }
  
  ReleaseDC(hWnd, hDC);
  DeleteDC(hDC);
 
  getchar();  // wait
  return 0;
}
Ene Uran 638 Posting Virtuoso

Ah, the old Turbo C bad habit clrscr() function. First try to make your program without it, it is rarely needed! You can replace one bad habit with another and use:

#include <stdlib.h> 

void clrscr(void)
{
  system ("cls");
  //system ("clear"); // for Unix
}

A more official version of a clrscr() function using Windows API is at:
http://www.daniweb.com/code/snippet232.html

SpS commented: Helps ~~SpS +3
Ene Uran 638 Posting Virtuoso

I think that Dev C++ follows the standard better, since it really uses a very common open source compiler. A program should close unless you make it wait within the code. Anything else is added by the IDE and is not standard.

Your version of Borland C++ is very old. Also Borland has a long history of straying from the standards. I am really surprised they are still around.

Ene Uran 638 Posting Virtuoso

1) Py2Exe is not easy to use!

2) Have you looked at the Py2Exe snippet at Daniweb? That should make it easier to use!

3) Have you been able to package any Python code into an exe?

4) Your program might be small, but there are some 'outhouse' modules that don't do well.

Ene Uran 638 Posting Virtuoso

The Fibonacci series of integers was orignally used in biology to predict the population increase of rodents, or the branching of the veins in a leaf (top to stem).

A Fibonacci number series is made by adding the current number to the previous number to get the next mumber. According to http://en.wikipedia.org/wiki/Fibonacci_number the series starts with 0, 1

This is one of the fastest ways to calculate the Fibonacci series:

def fibo3( n ):
    (current, previous) = (0, 1)
    k = n
    while k > 0:
    # use a tuple swap
        (current, previous) = (previous, current + previous)
    k -= 1
    return current
 
for n in range(13):
    print fibo3(n),
 
"""
example output:
0 1 1 2 3 5 8 13 21 34 55 89 144
"""

This is probably the sweetest way to create a list of the series:

fibo_list = [0,1]
for n in range(input('Enter an integer (>0): ')-1):
    fibo_list.append(fibo_list[-2] + fibo_list[-1])
print fibo_list
 
"""
example output:
Enter an integer (>0): 12
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
"""

Note: changed php code field tags, don't work properly any more.

Ene Uran 638 Posting Virtuoso

Your error trapping in the letter grades can be mildly improved:

s = 'A,A-,A+,B,B-,B+,C,C-,C+,D,D-,D+,F'
ps = """
Enter grade letters A through F, you
can also postfix A through D with + or -
(press just Enter to exit the loop when done): """
while True:
    x = raw_input(ps).upper()
    print x  # test
    if x == "":
        done = True
        break
    if x in s:
        break
    else:
        print "Error, use", s

# .........

There is another improvement possible when you assign a value to the grade letters:

letter = 'B+'  # test

# the index found is 0 to 4, and -1 if not found
ngrade = "FDCBA".find(letter[0])  

partial = 0.33  # or 0.25 this may vary with the school
if '+' in letter:
    ngrade = ngrade + partial
if '-' in x:
    ngrade = ngrade - partial
    
print ngrade  # test
Ene Uran 638 Posting Virtuoso

This if statment logic will not work for you if letter == "A" or "A-" or "A+": . You have to break it up, here is an example:

ps = """
Enter grade letters A through F, you
can also postfix A through D with + or -
(press just Enter to exit the loop when done): """
x = raw_input(ps).upper()

if 'A' in x:
    n = 4
elif 'B' in x:
    n = 3
elif 'C' in x:
    n = 2
elif 'D' in x:
    n = 1
elif 'F' in x:
    n = 0
    
partial = 0.33  # or 0.25 this may vary with the school
if '+' in x:
    n = n + partial
if '-' in x:
    n = n - partial

print n  # test
Ene Uran 638 Posting Virtuoso

Actually the Python25 version of wxPython has a flash player component. Here is the demo they give:

import  os
import  wx

if wx.Platform == '__WXMSW__':
    from wx.lib.flashwin import FlashWindow

from Main import opj

#----------------------------------------------------------------------

class TestPanel(wx.Panel):
    def __init__(self, parent, log):
        wx.Panel.__init__(self, parent, -1)
        self.pdf = None

        sizer = wx.BoxSizer(wx.VERTICAL)
        btnSizer = wx.BoxSizer(wx.HORIZONTAL)

        self.flash = FlashWindow(self, style=wx.SUNKEN_BORDER)
        self.flash.LoadMovie(0, 'file://' + os.path.abspath('data/Asteroid_blaster.swf'))

        sizer.Add(self.flash, proportion=1, flag=wx.EXPAND)

        btn = wx.Button(self, wx.NewId(), "Open Flash File")
        self.Bind(wx.EVT_BUTTON, self.OnOpenFileButton, btn)
        btnSizer.Add(btn, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)

        btn = wx.Button(self, wx.NewId(), "Open Flash URL")
        self.Bind(wx.EVT_BUTTON, self.OnOpenURLButton, btn)
        btnSizer.Add(btn, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)

        btnSizer.Add((50,-1), proportion=2, flag=wx.EXPAND)
        sizer.Add(btnSizer, proportion=0, flag=wx.EXPAND)

        self.SetSizer(sizer)
        self.SetAutoLayout(True)



    def OnOpenFileButton(self, event):
        dlg = wx.FileDialog(self, wildcard="*.swf")

        if dlg.ShowModal() == wx.ID_OK:
            wx.BeginBusyCursor()
            self.flash.LoadMovie(0, 'file://' + dlg.GetPath())
            wx.EndBusyCursor()

        dlg.Destroy()


    def OnOpenURLButton(self, event):
        dlg = wx.TextEntryDialog(self, "Enter a URL of a .swf file", "Enter URL")

        if dlg.ShowModal() == wx.ID_OK:
            wx.BeginBusyCursor()
            # setting the movie property works too
            self.flash.movie = dlg.GetValue() 
            wx.EndBusyCursor()

        dlg.Destroy()



#----------------------------------------------------------------------

def runTest(frame, nb, log):
    if wx.Platform == '__WXMSW__':
        win = TestPanel(nb, log)
        return win
    else:
        from Main import MessagePanel
        win = MessagePanel(nb, 'This demo only works on Microsoft Windows.',
                           'Sorry', wx.ICON_WARNING)
        return win


overview = """\
<html><body>
<h2>wx.lib.flashwin.FlashWindow</h2>

The wx.lib.pdfwin.FlashWindow class is yet another example of using
ActiveX controls from wxPython using the new wx.activex module.  This
allows you to use an ActiveX control as if it is a wx.Window, you can
call its methods, set/get properties, and receive events from the
ActiveX control in a very intuitive way.

<p> Using this class is simpler than ActiveXWrapper, doesn't rely …
Ene Uran 638 Posting Virtuoso

There are 4,017,010 characters in the authorized version of the Bible. War and Peace shouldn't be much larger.

Can you put the entire text of the Bible in one string and save it?
You can test it with this simple program, gives no problems on my PC:

# create a 5M character string
large_string = 'a' * 5000000

# open the file for writing
fout = open( 'String5M.txt', 'w' )
# write 5M character text
fout.write(large_string)
# close the file
fout.close()
Ene Uran 638 Posting Virtuoso

I looked at some of your questions.

#I AM CONFUSED RIGHT HERE. SHOULD IT BE:
 self.letter = letter

Since you only going to use the variable 'letter' in this particular method, you can keep it local, no need to add the 'self.' prefix.

for ch in letter:
            print ord(ch)

The function ord() gives you the ASCII value for the character, for instance 'A' would give you the integer 65.

stu.addLetterGrade(grade_str, credits)

Yes you are calling a method of the class instance 'stu'

You really wouldn't need a class for a simple program like this, but if you had a number of students you could create an instance for each, something like:

bill = Student("Bill Bunker", 0.0, 0.0)
tom = Student("Tom Tinker", 0.0, 0.0)
henry = Student("Hank Prince", 0.0, 0.0)

An extension of your program, so each student has his/her own class instance that could be saved with all the data when you are done.

Ene Uran 638 Posting Virtuoso

I've been trying to do that alteration that i talked above but i didin't get any results...can you give some advice how i would do that...thanks in adavance...:cheesy:

Take another look at:
http://www.daniweb.com/code/snippet604.html
I updated it with a few lines of code to add the edit feature. Thanks for bringing this to my attention.

Ene Uran 638 Posting Virtuoso

Okay, with all that Administrator stuff out of the way let's return to the "Starting Python" sticky.

If you had a list of names with title, first, middle and last name, how would you sort that list by the last name only? Well here is a solution commonly used to sort lists by item or modified item:

# sort a list of names by last name

def sort_names(names):
    """
    sort names by last name, avoiding title, first and middle names
    """
    names_mod = []
    for name in names:
        # split each name into a list
        name_list = name.split()
        # pick the last name from list
        last_name = name_list[-1]
        # create a list of temporary sublists [last_name, name] 
        names_mod.append([last_name, name])
    # sort the modified list of names inplace
    # this will sort by the first item in the 
    # sublists which is last_name
    names_mod.sort()
    # use list comprehension to
    # to remove the temporary last_name item
    return [name[1] for name in names_mod]

names = [
"Dr. Heidi Karin Hirsch",
"Miss Arlene Auerbach",
"Mr. and Mrs. Larry Zoom",
"Mr. Frank Paul Lummer",
"Vicepresident Colter"
]

print "Original list of names:"
for name in names:
    print name

print
print "List of names sorted by last name:"
names_sorted = sort_names(names)
for name in names_sorted:
    print name

"""
output -->
Original list of names:
Dr. Heidi Karin Hirsch
Miss Arlene Auerbach
Mr. and Mrs. Larry Zoom
Mr. Frank Paul Lummer
Vicepresident Colter

List of names sorted by last name:
Miss Arlene Auerbach
Vicepresident …
Ene Uran 638 Posting Virtuoso

If you use a test print statement above the line that puts a value into pricePass, you will find that the if condition doesn't allow you to get there, so the variable pricePass is valueless. Since Python defines the type of the variable by inference, it can't do that with a valueless variable.

Here is the offending condition:

if variable2[0] == passType:
                print variable2[1]
                print variable2[2]
                print "defining variable passPrice"  # test
                passPrice = float(price)*float(variable2[2])
                print passPrice

In your first version you never used passPrice, but price. So the runtime error did not come up.

Also a word of advice:
1) start your class names with a capital letter
2) create class instances like:
main = Main(root)
child = Child()
3) now you can get rid of the globals by associating the variables properly to the class instance via self. or the instance name.

Ene Uran 638 Posting Virtuoso

Can you give us your present code, just to see how this may fit in.

Ene Uran 638 Posting Virtuoso

You need to learn to experiment a little with the code, its fun!

# let user resize the Tkinter window, but do not move widgets
 
from Tkinter import *
 
root = Tk()
 
b1 = Button(root, text='Button 1')
# tells the widget not to expand into the packing cell
# and to anchor itself to the NW (upper left) corner
b1.pack(expand=NO, anchor=NW)

b2 = Button(root, text='Button 2')
# tells the widget not to expand into the packing cell
# and to anchor itself to the next free NW (upper left) corner
b2.pack(expand=NO, anchor=NW)
 
root.mainloop()
Ene Uran 638 Posting Virtuoso

Here is away to take care of chemical prefixes like 'o-', 'm-' and 'p-' when sorting. Just a little commonly used trick you can also use when sorting by your table columns:

# table of chemicals in stockroom as list of lists
# order --> stock number, chemical name, quantity (grams)

from operator import itemgetter

def sort_table(table, column_num):
    """
    sort a list of sublists that form a table by column number
    note that first column in table starts with column_num zero
    """
    return sorted(table, key=itemgetter(column_num))

def sort_chem(table):
    """
    this should take care of 'o-', 'm-' and 'p-' prefixes
    temporary change of sublist by adding modified chemical as first item
    sort this temp list and then rebuild by removing the temporary first item
    """
    temp = []
    for item in table:
        chem = item[CN]
        # removes leading 'o-' and adds '-o' to end for sort
        # you can add more similar prefixes here too
        if chem.startswith('o-'):
            chem = chem[2:] + '-o'
        if chem.startswith('m-'):
            chem = chem[2:] + '-m'
        if chem.startswith('p-'):
            chem = chem[2:] + '-p'        
        temp.append([chem,item])
    # this will sort by first item in each sublist
    temp.sort()
    new_table = []
    # rebuild the proper table
    for item in temp:
        #print item  # for test
        new_table.append(item[1])
    return new_table
 
def print_table(table):
    """
    pretty print the table
    """
    print '-'*66
    print "%-10s   %-40s  %s" % ('stock', 'chemical', 'quantity(g)')
    print '-'*66
    for item in table:
        print "%-10s   %-40s  %8d" % (item[0], item[1], item[2])
    print '-'*66

# assign constants
SN = 0  # index of …
Ene Uran 638 Posting Virtuoso

Method curselection() returns a tuple of the selections in case you selected more than one line, in your case pick tuple item zero. Change the your code line to reflect that:

passType=self.listPass.curselection()[0]
Ene Uran 638 Posting Virtuoso

Might have to add an edit option to the search_title() function. Good idea though! I am thinking of wrapping this all into a Tkinter GUI, that would make editing easier using an Entry widget.

Ene Uran 638 Posting Virtuoso

Some details on the use of modules in Python, heavily commented. Here is an example of a module:

# modules should be saved to the same folder as the 
# program or to folders listed in sys.path()

# save this module code as apple.py ...
# (module-name and file-name.py have to match, are case sensitive!)

def pieCookingStatus(cooking_time):
    if cooking_time < 35:
        print "Still cooking!"
    elif cooking_time < 40:
        print "Almost done!"
    else:
        print "Take pie out of the oven!"

def piePercentCooked(cooking_time):
    """consider 40 minutes the fully cooked time"""
    return 100 * cooking_time/40

# optional, specify version number of module
version = '1.2'

# this test runs when this code is used as a standalone program, 
# but not as an imported module of another program,
# then the namespace will be apple (name of module) and not __main__
if __name__ == '__main__':
    print "Pie is %d percent cooked." % piePercentCooked(33)
    pieCookingStatus(33)

Now the program that would use the above module:

# test the module apple.py

# import creates a namespace with the module's name (apple)
# also Python creates a precompiled bytecode file apple.pyc for speed
import apple

# optional, check version if it has been specified
if 'version' in dir(apple):
  print 'Version =', apple.version

# optional, show namespaces used
# note that namespace __name__ is assumed for this program
# you don't have to use it, but you have to prefix the 
# modules namespace to functions/variables of the module
# in this case prefix with apple …
Ene Uran 638 Posting Virtuoso

Looks like yo want to open a file called "50" even though the list is all integers.

mattyd commented: Ene Uran is always of Great Help. He\ She should Moderate at DaniWeb! +1
Ene Uran 638 Posting Virtuoso

There are a number of GUI toolkits for Python, but they are all Python wrappers for other languages. Tkinter is based on tcl, wxPython is based on wxWindows (works on Unix and Windows) written in C++, there is pygtk based on the ever so popular GTK, even pygame can be looked at as a GUI based on SDL.

There is nothing that should keep you back from writing a GUI from scratch. Not having seen such an effort by anyone I know, I supect that it might be a tad time consuming. Let me know when you have a product.

Ene Uran 638 Posting Virtuoso

More information on Unununium Python based OS, also kindly known as UUU, can be had at:
http://unununium.org/introduction

Ene Uran 638 Posting Virtuoso

You need to start a new thread with the proper title and give us the two files, so we can troubleshoot your program!

Ene Uran 638 Posting Virtuoso

Take a look at:
http://www.daniweb.com/code/snippet604.html
and use this database templet to create an address book. You can add a 'print address labels' feature to it.

The easiest would be to write the address labels to a file and use one of the editors or word processors to actually print it out to the printer.

Ene Uran 638 Posting Virtuoso

So that is where that went to! I thought I saw that for a moment in the stickies.

Ene Uran 638 Posting Virtuoso
Ene Uran 638 Posting Virtuoso

You can use the Python Image Library module to create thumbnails of images, see:
http://www.daniweb.com/code/snippet209.html

Ene Uran 638 Posting Virtuoso

Yes you can change the icon to anything you have:

from Tkinter import *
form1 = Tk()
# use an icon file you have in the working folder
form1.wm_iconbitmap('py.ico')
form1.wm_title('Title')
form1.mainloop()

You could create an icon that blends in with the title color, using something like LiquidIcon from www.x2studios.com (it's nice and free).

Ene Uran 638 Posting Virtuoso

You can use eval() to turn a string into an object.

Ene Uran 638 Posting Virtuoso

It depends what character follows the '\', if its 'n' then it becoames an escaped character like '\n' and will behave like a newline. I forgot to add the r in front to avoid this behaviour, like:

image_dir = r"C:\Documents and Settings\RockStar\Desktop\Python\drpython-161\Cards_gif\"

or you can do this:

image_dir = "C:\\Documents and Settings\\RockStar\\Desktop\\Python\\drpython-161\\Cards_gif\\"

That's the way it's done in C/C++ code.

Ene Uran 638 Posting Virtuoso

This is just a test frame where the robot moves at more or less at random, avoiding walls and blocks. When the robot sees an open coin it moves there and fetches it. Eventually it will get all the coins unless they are totally blocked in. Now one has to add look ahead strategy to minimize the moves. I am having fun with that!

# module robotlib.pyc from: 
# http://www.cs.sfu.ca/CC/120/ggbaker/assign-1067/assign4-robot

#from Tkinter import *
import random
from robotlib import *

# use one of the testboards (0 - 16)
r = Robot(testboard=12)

def look_around():
    """
    directions are N, E, S, W
    obj can be WALL, COIN, BLOCK (avoid hitting Block and WALL)
    dist is distance including the space of obj    
    """
    sensor_list = []
    for dir in [N, E, S, W]:
        obj, dist = r.sensor(dir)
        sensor_list.append((dist, obj, dir))
    return sensor_list

def check_coin():
    """
    check if there is a COIN in item[1] of the tuple
    """
    sensor_list = look_around()
    coin_list = []
    for item in sensor_list:
        if item[1] == COIN:
            coin_list.append(item)
    if coin_list:
        # sort the tuples so closest distance is first
        return sorted(coin_list)
    else:
        return False

def fetch_coin(coin_list):
    # move robot to closest=item[0] of tuple in coin_list[0]
    spaces = coin_list[0][0]
    # move direction=item[2] of tuple in coin_list[0]
    dir = coin_list[0][2]
    for x in range(spaces):
        r.move(dir)

def check_blockwall():
    """
    check if there is a BLOCK or WALL in item[1] of the tuple
    and is it next to the robot
    don't move in any of the directions in the …
Ene Uran 638 Posting Virtuoso

Solving a project's problems is really a good way to learn Python. You did well!

Ene Uran 638 Posting Virtuoso

Your error is in the line:

image_dir = "C:\Documents and Settings\RockStar\Desktop\Python\drpython-161\Cards_gif\C2.gif"

you have to change it to just the directory name:

image_dir = "C:\Documents and Settings\RockStar\Desktop\Python\drpython-161\Cards_gif\"
Ene Uran 638 Posting Virtuoso

If with 'simple' you mean 'not unnecessarily complex', I agree. Python is in many ways more powerfull than C++ or Java. Learning Python first might lead to a lot of pissing and moaning by the students who have to confront the often silly complexities of these other languages later. Well, good karma with your studies.

Have you started pseudo-coding your project? You might find out that it looks almost like Python syntax.

Ene Uran 638 Posting Virtuoso

Interesting project, I will play with it!
Just curious, is this a computer science course? Hard to digest, since most CS departments are bastions of conservative stuff like C++ and Java. Engineering and Science departments luckily have been more pragmatic and open to using Python.

Ene Uran 638 Posting Virtuoso

C:\Documents and Settings\RockStar\Desktop\Python\drpython-161\Cards_gifC2.gif looks like your image directory is C:\Documents and Settings\RockStar\Desktop\Python\drpython-161\ and your image file name is Cards_gifC2.gif . You wnat to make this C:\Documents and Settings\RockStar\Desktop\Python\drpython-161\Cards_gif\ and then the image name will be C2.gif

Ene Uran 638 Posting Virtuoso

You were very close:

# search lists

mammal_list = ['cat', 'dog', 'ape', 'cow']
bird_list = ['chicken', 'crow', 'quail', 'finch']

animal = raw_input("Enter an animal: ")

if animal in mammal_list:
    print "This animal is a mammal"
elif animal in bird_list:
    print "This animal is a bird"
else:
    print "This animal is not on any list"
Ene Uran 638 Posting Virtuoso

Avoiding the endless begin/end or curly braces, and also the end of line semicolons makes code simpler to read and understand. When you use an editor made for Python, indentations become easy to follow. You absolutley have to avoid mixing spaces with tabs in your indents. That's the main reason you have problems with other folks code! I religiously use spaces (4) only, since tab settings vary so much.

Ene Uran 638 Posting Virtuoso

If you don't want to get into the complexities of a standard sql database, you could simply modifiy my little structure/record based database in the Python code snippets at:
http://www.daniweb.com/code/snippet604.html

It allows you to load, save, add, list (as table), search, and delete data items. Need any help with that, just ask here.

Ene Uran 638 Posting Virtuoso

Hey thanks!
I enjoyed testing your nice code! I love to learn and really appreciate your problemsolving!

Ene Uran 638 Posting Virtuoso

This is the Python forum, I think you have to post this in the Java forum!

Ene Uran 638 Posting Virtuoso

Rather then MySQL you can use SQLite, sqlite3 is built into Python version 2.5 or you can download pysqlite2 for older versions.

Here is an example to create a database file:

# create a SQL database file
# pySQLite homepage (for Python24): http://initd.org/tracker/pysqlite
# tested with Python25 (has sqlite3 builtin)

try:
    from sqlite3 import dbapi2 as sqlite    # Python25
except ImportError:
    from pysqlite2 import dbapi2 as sqlite  # Python24 and pysqlite

# create a database:
con = sqlite.connect('mydatabase.db3')
cur = con.cursor()

# create a table:
cur.execute('create table clients (id INT PRIMARY KEY, name CHAR(60))')

# insert a single line:
client = (5,"John Smith")
cur.execute("insert into clients (id, name) values (?, ?)", client )
con.commit()

# insert several lines at once:
clients = [ 
(7,"Ella Fitzgerald"),
(8,"Louis Armstrong"),
(9,"Miles Davis")
]
cur.executemany("insert into clients (id, name) values (?, ?)", clients )
con.commit()

cur.close()
con.close()

Here is the example that reads the database file:

# read a SQL database file

try:
    from sqlite3 import dbapi2 as sqlite    # Python25
except ImportError:
    from pysqlite2 import dbapi2 as sqlite  # Python24 and pySqlite

# connect to an existing database
con = sqlite.connect('mydatabase.db3')
cur = con.cursor()

# get row by row
print "Row by row:"
cur.execute('select id, name from clients order by name;')
row = cur.fetchone()
while row:
    print row
    row = cur.fetchone()

# get all rows at once:
print "All rows at once:"
cur.execute('select id, name from clients order by name;')
print cur.fetchall()

cur.close()
con.close()
Ene Uran 638 Posting Virtuoso

You use something like shutil.copy(source_file, destination_file). You can't use the items in listbox2 since that's only the filename, so you have to use the items in the companion fullpath_list. The source_file is made up from the tuple's dirname and filename components. The destination_file is made up from the destination directory and the same filename.

Ene Uran 638 Posting Virtuoso

You are lucky getting a hold of Robin, the expert with wxPython. Did he ask you to buy his book on wxPython?

Ene Uran 638 Posting Virtuoso

Hi there danizzil14, I am giving you two examples of a simple Tkinter 'Hello World' code. The first one is without the use of class:

# Tkinter programming without a class

from Tkinter import *

def say_hi():
    # function for hi_button action
    # show new text on the label
    hi_label.config(text="Hi there, everyone!")


# create the basic window
root = Tk()

frame = Frame(root)
frame.pack()
# specify button action with command=function
# foreground/fg is red to color text
q_button = Button(frame, text=" QUIT ", fg="red", command=root.destroy)
q_button.pack(side=LEFT)

hi_button = Button(frame, text=" Hello ", command=say_hi)
hi_button.pack(side=LEFT)
# width of label is in characters
hi_label = Label(frame, text=" Hello, world! ", bg='yellow', width=20)
hi_label.pack(side=LEFT)

# start the event loop to respond to mouse clicks etc.
root.mainloop()

Here is the same program using a class structure:

# Tkinter programming using a class

from Tkinter import *

class App(object):
    """create a frame/window with 2 buttons and a label"""
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()
        # specify button action with command=function
        # foreground/fg is red to color text
        self.q_button = Button(frame, text=" QUIT ", fg="red", command=root.destroy)
        self.q_button.pack(side=LEFT)

        self.hi_button = Button(frame, text=" Hello ", command=self.say_hi)
        self.hi_button.pack(side=LEFT)
        # width of label is in characters
        self.hi_label = Label(frame, text=" Hello, world! ", bg='yellow', width=20)
        self.hi_label.pack(side=LEFT)

    def say_hi(self):
        # function for hi_button action
        # show new text on the label
        self.hi_label.config(text="Hi there, everyone!")

# create the basic window
root = Tk()
# instantiate the App class
app = App(root)
# start the event loop to respond to …