sneekula 969 Nearly a Posting Maven

Portable Python (aka. Flashcard Python or Python on a stick) comes with PyScripter and that IDE is a pleasure to code with. Python is a great language to solve scientific problems.

sneekula 969 Nearly a Posting Maven

Note that wxPython is the Python wrapper for the C/C++ based wxWindows.

sneekula 969 Nearly a Posting Maven

Put in a few test print() to catch the many errors.

sneekula 969 Nearly a Posting Maven

You could also use a list of instances of class Persons like shown in the example here:

# format: ni_number firstname lastname age
data_str = '''\
55512 Bart Simpson 45
45622 John Smith 58
46231 Alicia Sands 27
'''

fname = "data123.txt"

# write test data file
with open(fname, "w") as fout:
    fout.write(data_str)



class Persons:
    def __init__(self, ni_number, name, age):
        self.__ni_number = ni_number
        self.__name = name
        self.__age = age

    def show(self):
        '''for a quick test'''
        # formating string
        sf = " ni_number = {}\n name = {}\n age = {}\n"
        return sf.format(self.__ni_number, self.__name, self.__age)


# read the data file back in and process
with open(fname, "r") as fin:
    person_list = []
    for line in fin:
        mylist = line.split()
        print(mylist)  # test
        # unpack the list
        ni_number, first, last, age = mylist
        name = first + ' ' + last
        # create a list of instances of class Persons
        person_list.append(Persons(ni_number, name, age))

print('-'*20)
# test one of the instances
inst1 = person_list[0]
print(inst1.show())


''' console output -->
['55512', 'Bart', 'Simpson', '45']
['45622', 'John', 'Smith', '58']
['46231', 'Alicia', 'Sands', '27']
--------------------
 ni_number = 55512
 name = Bart Simpson
 age = 45

'''
sneekula 969 Nearly a Posting Maven
sneekula 969 Nearly a Posting Maven

So, where is the right post?

sneekula 969 Nearly a Posting Maven

Hint:

class Sentence:
    def __init__(self, text):
        self.text = text
        self.word_list = self.text.split()
        #print(self.word_list)  # test

    def get_first_word (self):
        return self.word_list[0]

    def get_all_words(self):
        "I let you work out what to return"
        pass

# create an instance of class Sentence(text)
# this is your input text
text = "I'm going back" 
sent1 = Sentence(text)

print(sent1.get_first_word())  # I'am

# get the whole text
print(sent1.text)  # I'm going back

# a hint for module sent1.get_all_words()
# create the words from self.word_list
for word in sent1.word_list:
    print(word)

'''
I'm
going
back
'''
sneekula 969 Nearly a Posting Maven

Your input to the class is your sentence/text, so put that into the class constructor __init__() as a parameter after self. Note that by convention class names are capitalized, it makes code much more readable:

class Sentence:
    def __init__(self, text):
        self.text = text

    def get_first_word (self):
        word_list = self.text.split()
        return word_list[0]


# create an instance
# Sentence(text)
# this is your input text
text = "Listen to the whisper, or wait for the brick." 
sent1 = Sentence(text)

print(sent1.get_first_word())  # Listen

# set up another instance
text = "My karma ran over your dogma." 
sent2 = Sentence(text)

print(sent2.get_first_word())  # My
sneekula 969 Nearly a Posting Maven

At this point you may want to actually study up on Python classes, you are making some major mistakes.

class Schedule:
    def __init__(self, course, points, level):
        self.course= course
        self.points = points
        self.level = level

    def get_course(self):
        return self.course

# create instances
# Schedule(course, points, level)
sched1 = Schedule("Programming101", 4, 1)
sched2 = Schedule("British103", 5, 3)
sched3 = Schedule("Biology102", 2, 1)

print(sched3.get_course())  # Biology102
# or
print(sched3.course)

print(sched1.points)  # 4
sneekula 969 Nearly a Posting Maven

Some observations are due:

class Patient(object):
    # by convention class names are capitalized
    def __init__(self, ID, name, bdate, gender, phone, address):
        # assing class parameters to instance self
        self.ID = ID
        self.name = name
        self.address = address
        # and so on

    def get_name(self):
        "this is a class method, first arg is self"
        print("Patient name = %s" % self.name)

    def set_name(self, newname):
        "method to change the name"
        self.name = newname



# create an instance of the class
# data have to be in this order
# Patient(ID, name, bdate, gender, phone, address)
john = Patient("5640","John","8/8/88","m","334-456-7898","60 Hilltop")

# get ID
print(john.ID) 

# use a method of the class instance
john.get_name()

# change the name
john.set_name("Johnathan Miller")
# now
john.get_name()

'''
5640
Patient name = John
Patient name = Johnathan Miller
'''
sneekula 969 Nearly a Posting Maven

Did you correct your code to this?

def inn():
    print position.get()
    if position.get()=='1':
        xx,yy=10,10
    elif position.get()=='2':
        xx,yy=60,60
    elif position.get()=='3':
        xx,yy=110,110
    window.create_image(xx,yy,image=pol3)
    top.destroy()
sneekula 969 Nearly a Posting Maven

Shows you how to assign a text font to the various Tkinter text oriented widgets:

''' tk_font_explore1.py
different ways to assign a text font to certain Tkinter widgets
snee
'''

try:
    # Python2
    import Tkinter as tk
    import tkFont as tkf
except ImportError:
    # Python3
    import tkinter as tk
    import tkinter.font as tkf

root = tk.Tk()
# set size of root
w = 350
h = 300
root.geometry("%dx%d" % (w, h))
root.title('setting Tkinter text fonts')

helv12 = tkf.Font(family="Helvetica", size=12, weight="bold")
helv16 = tkf.Font(family="Helvetica", size=16, weight="bold")

# FYI
# the instance of Font() can yield information
# get pixel width of a text in a given font, handy info
print(helv16.measure('label_2'))  # 71
print(helv16.cget('family'))      # Helvetica
print(helv16.actual())
''' result ...
{'family': 'Arial', 'weight': 'bold', 'slant': 'roman', 
'overstrike': 0, 'underline': 0, 'size': 16}
'''

frame = tk.Frame(root, bg='yellow')
frame.pack(side='top', fill='both', expand='yes')

label_1 = tk.Label(frame, text='label_1', font=helv12)
label_1.pack(pady=5)

label_2 = tk.Label(frame, text='label_2', font=helv16)
label_2.pack(pady=5)

# change helv16 (need to use a copy of the instance)
helv16a = helv16.copy()
helv16a.config(weight='normal', underline=1, slant='italic')
label_3 = tk.Label(frame, text='label_3', font=helv16a)
label_3.pack(pady=5)

# another way to set fonts using just a tuple
cosa24 = ('Comic Sans MS', 24, 'bold')
label_4 = tk.Label(frame, text='label_4', font=cosa24)
label_4.pack(pady=5)

# tuple examples of common fonts (some might be just on Windows)
#myfont = ('times', 20, 'bold')
#myfont = ('times', 12, 'normal')
#myfont = ('courier', 20, 'bold')
#myfont = ('helvetica', 20, 'bold italic')
#myfont = ('verdana', 20, 'bold italic')

# you can also use font designation this way
label_5 = tk.Label(frame, text='label_5', font='courier …
sneekula 969 Nearly a Posting Maven

Example:

class AirlineTicket:
    # by convention capitalize class names
    def __init__(self, name, orig, dest, travel_date, travel_class, price):
        # assign parameters to the instance self
        self.name = name
        self.origination = orig
        self.destination = dest
        self.travel_date = travel_date
        self.travel_class = travel_class
        self.price = price

    def info(self):
        # format the info string
        info_str = " %s travels %s class\n from %s to %s on %s"
        info = info_str % (self.name, self.travel_class, self.origination,
                           self.destination, self.travel_date)
        return info


# AirlineTicket(name, orig, dest, travel_date, travel_class, price)
# gether data
name = "Ted Trump"
orig = "JFK"
dest = "LAX"
travel_date = "12/23/2012"
travel_class = "first"
price = 1820.50

# create unique instance for this traveler
tedtru = AirlineTicket(name, orig, dest, travel_date, travel_class, price)

# test this instance
print(tedtru.info())

'''my result >>>
 Ted Trump travels first class
 from JFK to LAX on 12/23/2012
'''
sneekula 969 Nearly a Posting Maven

Sorry, rrashkin (Robert Rashkin) is correct.

sneekula 969 Nearly a Posting Maven
sneekula 969 Nearly a Posting Maven

Another look at the Tkinter GUI toolkit and its grid layout manager:

''' tk_grid_test101.py
explore the Tkinter grid layout
don't mix pack() and grid() within same frame container widget
place() and grid() can be used in the same frame

'''

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

root = tk.Tk()
w = h = 200
root.geometry("%dx%d" % (w, h))
root.title("buttons in frames")

frame1 = tk.Frame(root, bg='yellow')
frame1.pack(side='top', fill='both', expand='yes')

frame2 = tk.Frame(root, bg='green')
frame2.pack(side='top', fill='both', expand='yes')

# these buttons are in frame1
btn1 = tk.Button(frame1, text=" button1 ")
btn2 = tk.Button(frame1, text=" button2 ")
btn3 = tk.Button(frame1, text=" button3 ")
btn4 = tk.Button(frame1, text=" button4 ")
# these buttons are in frame2
btn5 = tk.Button(frame2, text=" button5 ")
btn6 = tk.Button(frame2, text=" button6 ")

# lay out buttons ...
# these buttons are in frame1
btn1.grid(row=0, column=0, pady=5)
btn2.grid(row=1, column=0)
btn3.grid(row=1, column=1, padx=5)
btn4.grid(row=1, column=2)
# these buttons are in frame2
btn5.grid(row=0, column=0, pady=5)
btn6.grid(row=1, column=0)

root.mainloop()

Thanks vegaseat for this hint!
Display --> http://prntscr.com/l8g34

sneekula 969 Nearly a Posting Maven

First of all, let us know which GUI toolkit you are using and give us some of your pertinent code.

sneekula 969 Nearly a Posting Maven

from connect4cell2 import Connect4Cells
make sure the file you are importing is saved as connect4cell2.py

self.cells = Connect4Cells(rows, columns, 3)
self.cells can now use any of the instances methods like
row_flag = self.cells.checkRow(rowIndex)
you have to supply the rowIndex value

sneekula 969 Nearly a Posting Maven

The speed of reading and writing huge files is limited by your hardware.

sneekula 969 Nearly a Posting Maven

line 15
return estimate
should be outside the loop

sneekula 969 Nearly a Posting Maven

You can insert a print statement for testing the progress, and see how the higher values bubble to the end and lower values bubble to the start of the list:

myList=[43,21,12,80,3,2,35]
print(myList)
print('-'*30)

end = len(myList)-1
while (end != -1):
    swapped = -1
    for i in range(0, end):
        if myList[i] > myList[i+1]:
            temp = myList[i]
            myList[i] = myList[i+1]
            myList[i+1]= temp

            print(myList)  # test print to follow progress of sort

            swapped = i
    end = swapped

print('-'*30)
print(myList)

'''
[43, 21, 12, 80, 3, 2, 35]
------------------------------
[21, 43, 12, 80, 3, 2, 35]
[21, 12, 43, 80, 3, 2, 35]
[21, 12, 43, 3, 80, 2, 35]
[21, 12, 43, 3, 2, 80, 35]
[21, 12, 43, 3, 2, 35, 80]
[12, 21, 43, 3, 2, 35, 80]
[12, 21, 3, 43, 2, 35, 80]
[12, 21, 3, 2, 43, 35, 80]
[12, 21, 3, 2, 35, 43, 80]
[12, 3, 21, 2, 35, 43, 80]
[12, 3, 2, 21, 35, 43, 80]
[3, 12, 2, 21, 35, 43, 80]
[3, 2, 12, 21, 35, 43, 80]
[2, 3, 12, 21, 35, 43, 80]
------------------------------
[2, 3, 12, 21, 35, 43, 80]
'''

Also the C type swap

        temp = myList[i]
        myList[i] = myList[i+1]
        myList[i+1]= temp

can be replaced with a Python tuple swap

myList[i+1], myList[i] = myList[i], myList[i+1]

sneekula 969 Nearly a Posting Maven

To pass an argument in the button command use lambda:

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def click(s):
    """called with lambda"""
    if s == "one":
        root.title("Button one has been clicked")
    else:
        root.title("Button two has been clicked")


root = tk.Tk()

b1 = tk.Button( text="one", command=lambda: click("one") )
b1.pack(padx=150, pady=10)

b2 = tk.Button( text="two", command=lambda: click("two") )
b2.pack(pady=10)

root.mainloop()

You could create your buttons in a loop, but it would be quite cumbersome. It would be difficult to maintain a meaningful variable name for each button. Since you only have 6 buttons it wouldn't be worth it.

sneekula 969 Nearly a Posting Maven

Let's give it a try:

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

app = QApplication(sys.argv)

# ----- start your widget test code ----


# create the label
label = QLabel()
label.show()
# insert a text string
label.setText('Hello fron DaniWeb!')
print(sys.argv)


# ---- end of widget test code -----

app.exec_()

''' my console output -->
['C:\\Python33\\BS\\pqt_sys_argv.py']
'''

QApplication() expects a list, but you can feed it an empty list if you don't want to putz around with sys.argv

from PyQt4.QtCore import *
from PyQt4.QtGui import *

app = QApplication([])

# ----- start your widget test code ----


# create the label
label = QLabel()
label.show()
# insert a text string
label.setText('Hello fron DaniWeb!')


# ---- end of widget test code -----

app.exec_()
Gribouillis commented: good help +13
sneekula 969 Nearly a Posting Maven

A helper function will do:

'''sort_alpha_only1.py
sort only the alphabetic part of a word
has:
['test1_two', 'testOne', 'testTwo', 'test_one']
wants:
['testOne', 'test_one', 'test1_two', 'testTwo']
'''

def alpha_only(word):
    '''
    helper function to sort only the alphabetic part of a word
    '''
    word = "".join(c for c in word if c.isalpha())
    return word.lower()

list1 = ['test1_two','testOne','testTwo','test_one']
list2 = sorted(list1, key=alpha_only, reverse=False)
print(list2)

'''
['testOne', 'test_one', 'test1_two', 'testTwo']
'''
sneekula 969 Nearly a Posting Maven

You mean something like this:

mylist = []
for c1 in range(65, 90):
    for c2 in range(65, 90):
        mylist.append((c1<<16) + (c2<<8) + 32)

print(mylist)

Or this:

import array

myarray = array.array('I', [])
for c1 in range(65, 90):
    for c2 in range(65, 90):
        myarray.append((c1<<16) + (c2<<8) + 32)

print(myarray)
sneekula 969 Nearly a Posting Maven
sneekula 969 Nearly a Posting Maven

Okay rude&crude use the Windows Environment Variable

sneekula 969 Nearly a Posting Maven

This will do stuff if x is not zero, False, None or empty

if x:
  do stuff
sneekula 969 Nearly a Posting Maven

You can also add within the program that needs it:

# add these lines to the beginning of your program
import sys
# for instance add myfolder123 folder to PYTHONPATH
sys.path.append(r'C:\Python27\Lib\site-packages\myfolder123')
sneekula 969 Nearly a Posting Maven

Windows note: control panel>System>Advanced>Environment Variable
allows you to add PYTHONPATH + directories used

sneekula 969 Nearly a Posting Maven

"You only live once, but if you do it right, once is enough."
~~~ Mae West

sneekula 969 Nearly a Posting Maven

Write a letter to your government to outlaw boredom!

In other words, get involved in politics and you never get bored.

sneekula 969 Nearly a Posting Maven

At least in the USA July 2012 was the hottest in recorded history.

sneekula 969 Nearly a Posting Maven

Visual Python Tkinter IDE is a very badly written piece of software with lots of errors.
I don't recommend using it unless you want to waste a lot of time.

sneekula 969 Nearly a Posting Maven
sneekula 969 Nearly a Posting Maven

Here is an example that gets the size of the image and centers the splash screen:

# a Tkinter splash screen 
# (uses a GIF image file, does not need PIL)
# tested with Python27

import Tkinter as tk

class SplashScreen(tk.Toplevel):
    def __init__(self, master, image=None, timeout=1000):
        """
        create a splash screen from a specified image file
        keep splash screen up for timeout milliseconds
        """
        tk.Toplevel.__init__(self, master, relief='raised', borderwidth=5)
        self.main = master

        # don't show main window
        self.main.withdraw()
        self.overrideredirect(1)

        # use Tkinter's PhotoImage for .gif files
        self.image = tk.PhotoImage(file=image)
        self.after_idle(self.centerOnScreen)

        self.update()
        self.after(timeout, self.destroySplash)

    def centerOnScreen(self):
        self.update_idletasks()
        # get the width and height of the image
        self.width, self.height = self.image.width(), self.image.height()

        xmax = self.winfo_screenwidth()
        ymax = self.winfo_screenheight()

        x0 = self.x0 = xmax/2 - self.width/2
        y0 = self.y0 = ymax/2 - self.height/2
        self.geometry("%dx%d+%d+%d" % (self.width, self.height, x0, y0))
        self.createSplash()

    def createSplash(self):
        # show the splash image
        self.canvas = tk.Canvas(self, height=self.height, width=self.width)
        self.canvas.create_image(0,0, anchor='nw', image=self.image)
        self.canvas.pack()

    def destroySplash(self):
        # bring back main window and destroy splash screen
        self.main.update()
        self.main.deiconify()
        self.withdraw()

# test it ...
if __name__ == "__main__":
    import os

    # main window
    root = tk.Tk()
    s = "This was a test of the gif image splash screen"
    lbl = tk.Label(root, text=s, bg='yellow')
    lbl.grid(row=0, column=0, padx=5, pady=5)

    # pick a splash screen GIF image file you have in the working folder
    # otherwise give full path
    image_file = "TWEEK600.gif"
    assert os.path.exists(image_file)
    s = SplashScreen(root, timeout=5000, image=image_file)

    root.mainloop()
Ene Uran commented: thank you +12
sneekula 969 Nearly a Posting Maven

wxMediaCtrl uses native backends to render media,
for example on Windows there is a ActiveMovie/DirectShow backend,
and on Macintosh there is a QuickTime backend

backend options:.

wx.MEDIABACKEND_GSTREAMER    for linux/unix
wx.MEDIABACKEND_QUICKTIME       for Mac 
sneekula 969 Nearly a Posting Maven
# find the version of Python you are using

import platform

print(platform.python_version())
sneekula 969 Nearly a Posting Maven

This is really a question of what version of Python you are using.
If you use Python2 then input() is for numeric input, but with Python3 you will get strings.

With Python27 this will work:

# Python27

def main():
    print("Adding:")
    a = input("Please select a number:")
    b = input("And another one:")
    c = input("One more please:")
    d = a+b+c
    print(d)


main()

'''possible result ...

Adding:
Please select a number:1
And another one:2
One more please:3
6

'''
sneekula 969 Nearly a Posting Maven

Use the Python module timeit to test the speed of a function. Here is an easy way:

'''get_timing.py
use Python module timeit in a wrapper
modified vegaseat code
works with Python2 and Python3
'''

def get_timing(fs, number=10000, module="__main__"):
    """
    this wrapper can be used to time any function
    pass full function call in as a string eg. 'func(arg1, arg2)'
    number = number of timeit loops
    module namespace is autodetected
    """
    import timeit
    import inspect
    # extract function name
    q1 = fs.split('(')
    f = eval(q1[0])
    # extract arguments
    q2 = q1[1].strip(')')
    if q2:
        args = eval(q2)
    else:
        args = None
    name = f.__name__
    # get module namespace
    module = inspect.getmodule(f).__name__
    if args == None:
        st1 = "%s()" % (name)
    elif type(args) == tuple:
        st1 = "%s%s" % (name, args)
    elif type(args) == str:
        st1 = "%s('%s')" % (name, args)
    else:
        st1 = "%s(%s)" % (name, args)
    st2 = "from %s import %s" % (module, name)
    t = timeit.Timer(st1, st2)
    # elapsed time is in microseconds
    print("Function %s took %.2f microseconds/pass" % \
        (st1, 1000000*t.timeit(number=number)/number))
    # optional ...
    return eval(fs)

def gcd3(x, y):
    """greatest common denominator, non-recursive"""
    while y:
        x, y = y, x % y
    return x

def test():
    pass

# testing ...
if __name__=="__main__":
    import math

    # no arguments
    print(get_timing('test()'))

    # one argument
    print(get_timing("math.log(1000)"))

    # two arguments
    print(get_timing('gcd3(1251, 3357)'))
vegaseat commented: nice +14
sneekula 969 Nearly a Posting Maven

What does this little test do?

import csv

csv_fn = 'out.csv'
out_csv = csv.writer(open(csv_fn, 'wb'))

print(out_csv)
sneekula 969 Nearly a Posting Maven

Developing with Python will be simpler and faster, however the product might be slower. There is a spellchecker module for Python and a couple of GUI tool-kits.

sneekula 969 Nearly a Posting Maven

You can also work on a novel and let Python write it.

sneekula 969 Nearly a Posting Maven

You can also use Python's built-in % format specifiers:

for outer in range(1,13):
    print '\t'.join("%5d"%(outer*inner) for inner in range(1, 13))
sneekula 969 Nearly a Posting Maven

Just wondered which computer language is best suited for preteen students.
Any ideas or experiences?

sneekula 969 Nearly a Posting Maven

The smarter you are, the more you dream.

sneekula 969 Nearly a Posting Maven

We must believe in luck. For how else can we explain the success of those we don't like?
~~~ Jean Cocteau

sneekula 969 Nearly a Posting Maven

English nursery rhyme:
The rose is red, the violet's blue
The honey's sweet, and so are you
Thou are my love and I am thine
I drew thee to my Valentine
The lot was cast and then I drew
And Fortune said it shou'd be you.

sneekula 969 Nearly a Posting Maven

I once received an email that included the line:

"By the way, what does BTW stand for?"

sneekula 969 Nearly a Posting Maven

A classic one seater