vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Lack of money is the root of all evil.
-- Senator Burnsbee

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

After all is said and done, more is said than done.
-- Hank Dryer

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Show us the code you have and the error message, so we can help you.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I bought an Apple computer,
there was a worm in it!
-- Rodney Dangerfield

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The arguments/parameters for the button are
wx.Button(parent, id, label, pos, size, style, name)
A number of these arguments have defaults, but parent has to be specified.
It is the frame, panel or other surface where the button will appear on.
In your case win is the parent and is the instance of that particular frame.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A temporary test print might shed some light on the workings of the code ...

def insertion_sort( lista ):
    for i in range ( 1, len( lista ) ):
        save = lista[i]
        j = i
        while ( j > 0 and lista[j - 1] > save ):
            lista[j] = lista[j - 1];
            j -= 1
        lista[j] = save
        # optionally show sort progress
        print( lista )


lista = ['j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
insertion_sort(lista)

''' my result>>>
['i', 'j', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
['h', 'i', 'j', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
['g', 'h', 'i', 'j', 'f', 'e', 'd', 'c', 'b', 'a']
['f', 'g', 'h', 'i', 'j', 'e', 'd', 'c', 'b', 'a']
['e', 'f', 'g', 'h', 'i', 'j', 'd', 'c', 'b', 'a']
['d', 'e', 'f', 'g', 'h', 'i', 'j', 'c', 'b', 'a']
['c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'b', 'a']
['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'a']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
'''

Actually, you can use Python module bisect to do just what you want ...

# using module bisect to insert a string into a sorted
# list of strings at the correct position

import bisect

name_list = ['Eva', 'Pam', 'Dee', 'Amy', 'Gin', 'Joy', 'Mae']
# binary searches require a sorted list
name_list.sort()

print(name_list)

# insert a new name at the correct position in the list
new_name = 'Kay'
bisect.insort_left(name_list, new_name)

print(name_list)

''' my result>>>
['Amy', …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Asking any user to enter 100 numbers is simply an atrocity. Let's say the user makes a mistake at the 87th number, you have to build in a way to recover without having to start with the first number again, or the nice piece of hardware may end up on the floor of frustration!

Anyway, which version of Python are you using?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Every now and then there is a demand for this sort of information ...

# create some Tkinter canvas shapes
# show their names when clicked

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

def clicked(event):
    """display the clicked widgets's name"""
    root.title( shape_dict[cv.find_withtag('current')[0]] )

def create_shapes():
    """function keeps local dictionary vars() clean"""
    line1 = cv.create_line(0, 10, 200, 10, fill='red', width=5, tags='click')
    line2 = cv.create_line(0, 30, 200, 30, fill='blue', width=5, tags='click')
    line3 = cv.create_line(0, 50, 200, 50, fill='green', width=5, tags='click')
    rect1 = cv.create_rectangle(50, 70, 150, 85, fill='magenta', tags='click')
    oval1 = cv.create_oval(10, 70, 40, 85, fill='red', tags='click')
    print(oval1, cv.type(oval1))  # test --> (5, 'oval')
    # reverse local dictionary vars()
    # keys are now numbered in order of creation, values are the names
    return dict((v, k) for (k, v) in vars().items())
    

root = tk.Tk()

cv = tk.Canvas(root, width=200, height=100, bg='white')
cv.pack()

shape_dict = create_shapes()
# test
print(shape_dict)

# left mouse click = '<1>'
cv.tag_bind('click', '<1>', clicked)

root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

One way to get some sound into your Tkinter GUI toolkit code ...

# play a wave sound file with Tkinter using the module pygame
# pygame is free from: http://www.pygame.org/
# tested with Python26, Python31 and pygame1.9.1  vegaseat

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

def pg_play_sound(sound_file):
    """
    uses the pygame mixer
    will load the whole sound into memory before playback
    """
    sound = pg.mixer.Sound(sound_file)
    clock = pg.time.Clock()
    sound.play()
    # how often to check active playback
    frame_rate = 30
    while pg.mixer.get_busy():
        clock.tick(frame_rate)

def play_sound():
    pg_play_sound(sound_file)


# initiate the mixer with these values for good sound
FREQ = 18000   # play with this for best sound
BITSIZE = -16  # here unsigned 16 bit
CHANNELS = 2   # 1 is mono, 2 is stereo
BUFFER = 1024  # audio buffer size, number of samples
pg.mixer.init(FREQ, BITSIZE, CHANNELS, BUFFER)
# or use just default values (sounds a bit more tinny)
#pg.mixer.init()

root = tk.Tk()
# use width x height + x_offset + y_offset (no spaces!)
root.geometry("250x50+50+30")
root['bg'] = 'green'

# pick a .wav sound file you have in the working directory
# or give the full path
sound_file = "Chimes.wav"
root.title(sound_file)
s = "Play " + sound_file
b1 = tk.Button(root, text=s, command=play_sound)
b1.pack(padx=30, pady=5)

root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

"Eating my own words has never given me indigestion."
-- Sir Winston Leonard Spencer-Churchill

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The PIL show() function internally saves a temporary bitmap file, then calls the default viewer to show it. Looks like your default viewer does not accept command line image files. You can use module webbrowser instead ...

from PIL import Image, ImageDraw
from random import randint

picture = Image.new("RGB", (600, 600))
artist = ImageDraw.Draw(picture)

for i in range(100):
    x1, y1 = randint(0, 600), randint(0, 600)
    x2, y2 = randint(0,600), randint(0,600)
    color = (randint(0, 255), randint(0, 255), randint(0, 255))
    width = randint(2, 20)
    artist.line([x1, y1, x2, y2], color, width)

#picture.convert("RGB")
#picture.show()
# save the image to show it with the web browser's viewer
filename = "aa_image.jpg"
picture.save(filename)
import webbrowser
webbrowser.open(filename)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
# I assume you have created the total active_days_list

active_weeks_list = [
'0000000000111111111100000000000000000000000000000000',
'0000000001000000000000000000000000000000000000000000',
'0000000000000000000000000011111111000011100000000000',
'0000000000000101111100000000000000000000000000000000',
'0000000001111111111100000000000000000000000000000000',
'0000000000111111111100000000000000000000000000000000',
'0000000000000000000000000001111111000001100000000000',
'0000000000111000000000000000000000000000000000000000',
'0000000001111111111100000000000000000000000000000000',
'0000000000000000000000000011111111000011100000000000',
'0000000000000000000000000011111111000011100000000000',
'0000000000000111111100000000000000000000000000000000',
'0000000000000000000000000000000000000000001000000000',
'0000000000000000000000000001111111000001100000000000',
'0000000000000000101000000000000000000000000000000000',
'0000000000000000000000000000000000000001000000000000',
'0000000001111111111100000000000000000000000000000000'
]

for active_weeks in active_weeks_list:
    for ix, week in enumerate(active_weeks):
    if week == '1':
        print(active_days_list[ix])
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Something like this should help ...

active_days = [
[1, '27/07/2009', '28/07/2009', '29/07/2009', '30/07/2009', '31/07/2009'],
[2, '03/08/2009', '04/08/2009', '05/08/2009', '06/08/2009', '07/08/2009'],
[3, '10/08/2009', '11/08/2009', '12/08/2009', '13/08/2009', '14/08/2009'],
[4, '17/08/2009', '18/08/2009', '19/08/2009', '20/08/2009', '21/08/2009']
]

active_weeks= '0010'
for ix, week in enumerate(active_weeks):
    if week == '1':
        print(active_days[ix])

""" result >>>
[3, '10/08/2009', '11/08/2009', '12/08/2009', '13/08/2009', '14/08/2009']
"""

The Python module calendar should be of great help too!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you use the Python write() function to write to a text file, Windows normally puts in a '\r\n' line separator. This is somewhat annoying for Linux users that expect only a '\n' newline character. Python3 has solved this with the newline keyword when you open a file for writing ...

# write text file Unix style with only '\n' as line separator

text = """\
This broom does not actually fly.
For indoor or outdoor use only.
Product will be hot after heating.
Do not use while sleeping.
Open bottle before drinking.
Keep away from children.
Some assembly required.
"""

fname = "atest7.txt"

# Windows would normally use '\r\n'
# specify Unix style '\n' this way, needs Python3
fout = open(fname, "w", newline='\n')
fout.write(text)
fout.close()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You seem to have a tuple of numeric strings. Change it to a list this way ...

data_tuple = '4', '3', '1', '3', '2', '1'
data_list = [int(item) for item in data_tuple]
print(data_list)  # [4, 3, 1, 3, 2, 1]
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A simple template to experiment with PyQT widgets ...

# a simple template to test PyQT widgets
# PyQT free from:
# http://www.riverbankcomputing.co.uk/software/pyqt/download
# used Windows installer PyQt-Py3.1-gpl-4.7.2-1.exe
# tested with PyQT4.7 and Python3.1

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

app = QApplication([])
# create the window and set the title
win = QWidget()
# setGeometry(x_pos, y_pos, width, height)
# 1, 1 --> widget will expand to fit lable size
win.setGeometry(100, 150, 1, 1)


html_code = """\
<h1><i>Hello </i>
<font color=red>PyQT!</font><h1>
"""
# create the label and insert html code as text
label = QLabel(html_code)

# use the grid layout manager
grid = QGridLayout()
# addWidget(widget, row, column, rowSpan=1, columnSpan=1)
grid.addWidget(label, 0, 0)
win.setLayout(grid)


win.show()
app.exec_()

You can even go simpler ...

# a very simple template to test PyQT widgets

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

app = QApplication([])


html_code = """\
<h1><i>Hello </i>
<font color=red>PyQT!</font><h1>
"""
# create the label and insert html code as text
label = QLabel(html_code)
label.show()


app.exec_()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you bind a Tkinter widget to an event, normally only the event information is passed to the function responding to the specific event like a mouse click. Python allows you to expand the event handler to include any number of values to be passed on. Here is a typical example ...

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Check if the order of installations (Python first then Blender) makes a difference.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

write() takes a string parameter
concatenation needs string types
so try this ...

counter = 3
item = "milk"

s = "Error - invalid first qualifier (Line " + str(counter) + ")\n" + item
print(s)  # test for write(s)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
PythonNewbie2 commented: Good call - I'll see if it works :) +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Using the Tkinter GUI toolkit to create five pointed stars ...

# explore Tkinter's
# canvas.create_polygon(xy_list, fill)
# to create five pointed stars

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

# create the root window and set title too
root = tk.Tk(className="five pointed stars")

w = 400
h = 400
x = 50
y = 100
# set x, y position of root
root.geometry("+%d+%d" % (x, y))

# pairs of x,y coordinates for the 10 corners of a five pointed star
star = [10,40,40,40,50,10,60,40,90,40,65,60,75,90,50,70,25,90,35,60]

# create the drawing canvas
canvas = tk.Canvas(root, width=w, height=h, bg='white')
canvas.pack()

canvas.create_polygon(star, fill='red')

# shift the star x,y by 70
star1 = [k+70 for k in star]
canvas.create_polygon(star1, fill='blue')

# shift the star x,y by 140
star2 = [k+140 for k in star]
canvas.create_polygon(star2, fill='maroon')

# double the size and shift the star x,y by 180
star3 = [k*2+180 for k in star]
canvas.create_polygon(star3, fill='green')

root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Smimming is fun, everybody should do it! You can do it with your Wii.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Starting with Python3
class Class1(object):
can be written
class Class1:
object is now automatically inherited.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Python is a modular language, and half the difficulty is discovering these optimized little gems ...

# use Python module textwrap to break up a long text into
# columns of maximum 40 characters, words are kept whole

import textwrap

description = """\
Ngqolomashe was hit with fists and open hands, kicked in the face
and strangled by about 15 people. His head was also hit against a
metal parking meter and he was seen to be bleeding profusely.  """


# blank lines are ignored
sentence = textwrap.fill(description, 40)

print(sentence)

""" result >>>
Ngqolomashe was hit with fists and open
hands, kicked in the face and strangled
by about 15 people. His head was also
hit against a metal parking meter and he
was seen to be bleeding profusely.
"""
Gribouillis commented: very good comments ! +4
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Python programming can have its lighter moments. Here we use one of those moments to draw an optical illusion using the Tkinter canvas to draw a rectangle, some lines and circles.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You have to make the variable pass_entered available to the function. The simplest way is to use global pass_entered. There were some other errors ...

import time
import Tkinter as tk
import ctypes

root = tk.Tk()
pass_entered = False

def show_pw():
    global pass_entered
    pw = pw_entry.get()
    if pw == "password":
        label2['text'] = pw
        pass_entered = True
        print pw  # test
        #return pass_entered  # pass_entered goes no-where
        return
    else:
        label2['text'] = "Sorry, wrong pass"

def logoff(mins):
    global pass_entered
    label1.config(height=3, font=('times', 12, 'bold'))
    for k in range(int(mins), 0, -1):
        label1["text"] = str(k) + ' Minutes remaining'
        root.update()
        time.sleep(5)
        print k, pass_entered  # test
        if pass_entered == True:
            break
    label1["text"] = "Now logging off"
    #ctypes.windll.user32.LockWorkStation()  # remove comment later

pw_entry = tk.Entry(root, show="*")
pw_entry.focus()
button = tk.Button(root, text='override', command=show_pw)
label1 = tk.Label(root)
label2 = tk.Label(root)

pw_entry.pack()
button.pack()
label1.pack()
label2.pack()

logoff(100)

root.mainloop()
leegeorg07 commented: great code and a great help +3
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Exploring a Tkinter list box ...

# load a Tkinter listbox with data
# color alternate lines
# and select a listbox item with the mouse

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

def get_list(event=None):
    """
    function to read the listbox selection
    and put the result in a label widget
    """
    # get selected line index
    index = listbox.curselection()[0]
    # get the line's text
    seltext = listbox.get(index)
    # put the selected text in the label
    label['text'] = seltext

# the main window
root = tk.Tk()

# create a label (width in characters)
label = tk.Label(root, width=15)
label.pack()

# create a listbox (height in characters)
listbox = tk.Listbox(root, height=15)
listbox.pack()

friend_list = [
'Stew', 'Tom', 'Jens', 'Adam', 'Al', 'Ethel',
'Barb', 'Tiny', 'Tim', 'Pete', 'Sue', 'Zack',
'Frank', 'Gustav', 'Ted', 'Morgan', 'Karen']

# load the listbox
for index, item in enumerate(friend_list):
    listbox.insert('end', item)
    # optionally color alternate lines
    if index % 2:
        listbox.itemconfig(index, bg='light blue')
    
# left mouse click on a list item to display selection
listbox.bind('<ButtonRelease-1>', get_list)
# use mouse wheel to scroll listbox items, focus first
listbox.focus()

root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

"Too much information kills your fantasy"
-- Andy Warhole

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is one way you can approach your problem ...

import pprint

test_data = """\
(231.2314,32434.344,134.2342,345.345,1234.45)
(2323.567,32.6754,12323.8776,12323.575,233.5673)
"""
# write the test data file out
fname = "atest.txt"
fout = open(fname, "w")
fout.write(test_data)
fout.close()

# read the test data file back in
fin = open(fname, "r")
data_list1 = []
data_list2 = []
for line in fin:
    # strip whitespace
    line = line.strip()
    # strip '('
    line = line.strip('(')
    # srip ')'
    line = line.strip(')')
    #convert string to list of floats at the comma
    data_float = [float(x) for x in line.split(',')]
    # create a list of line sublists
    data_list1.append(data_float)
    # create one list of all data items
    data_list2.extend(data_float)

pprint.pprint( data_list1 )

print('-'*30)

pprint.pprint( data_list2 )

""" result (typical binary rep of floats) >>>
[[231.23140000000001,
  32434.344000000001,
  134.23419999999999,
  345.34500000000003,
  1234.45],
 [2323.567,
  32.675400000000003,
  12323.8776,
  12323.575000000001,
  233.56729999999999]]
------------------------------
[231.23140000000001,
 32434.344000000001,
 134.23419999999999,
 345.34500000000003,
 1234.45,
 2323.567,
 32.675400000000003,
 12323.8776,
 12323.575000000001,
 233.56729999999999]
"""

Some numbers look a little strange at first, but most computer languages handle floating point numbers as binary numbers which can introduce a very tiny error with some numbers.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

No news is good news!
So send your friends empty envelopes.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I would simply use
entry.insert('end', btn)

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Your problem is not with app.destroy(), but with track.stop()

self.track is an instance name (instance of pygame Sound class) in class SoundPanel and needs to be associated with the proper instance of class SoundPanel
like panel1.track.stop(), panel2.track.stop() etc.

I took the liberty to play around with your previous program (nice programming effort by the way!) and came up with this ...

# sound_panel2.py
# this can be a module

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

# create class
class SoundPanel(tk.Frame):
    def __init__(self, parent, mixer, sound_file):
        tk.Frame.__init__(self, parent)
        self.track = mixer.Sound(sound_file)
        self.track_playing = tk.IntVar()
        
        track_button = tk.Checkbutton(self, variable=self.track_playing,
            command=self.track_toggle, text=sound_file)
        track_button.pack(side='left')
        self.volume = tk.DoubleVar()
        self.volume.set(self.track.get_volume())
        volume_scale = tk.Scale(self, variable=self.volume, 
            from_=0.0, to=1.0,
            resolution=0.1, command=self.change_volume,
            label="Volume", orient='horizontal')
        volume_scale.pack(side='right')
        
    def track_toggle(self):
        if self.track_playing.get() == 1:
            self.track.play(loops = -1)
        else:
            self.track.stop()
            
    def change_volume(self, v):
        self.track.set_volume(self.volume.get())

# test the module
if __name__ == '__main__':
    # pick a sound file you have in the working folder
    # or supply full path
    soundfile1 = "Chimes.wav"
    soundfile2 = "DingDong.wav"

    # create main window
    root = tk.Tk()
    root.title("Sound Mixer")

    # create mixer
    mixer = pygame.mixer
    mixer.init()

    # create instances
    panel1 = SoundPanel(root, mixer, soundfile1)
    panel1.pack()
    panel2 = SoundPanel(root, mixer, soundfile2)
    panel2.pack()

    def shutdown():
        # self.track is a variable in class SoundPanel and 
        # needs to be associated with the proper instance
        panel1.track.stop()
        panel2.track.stop()
        root.destroy()
        
    # shut it down orderly
    root.protocol("WM_DELETE_WINDOW", shutdown)
    # run the event loop
    root.mainloop()

I prefer root over app, just a personal …

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

One error I can see in line 19 of the module ...
to 1.0,
should be
to = 1.0,

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Since the Tkinter GUI toolkit is included with just about all Python versions, you can use it for a convenient anykey() function in your console applications. The anykey() function will wait until any key on the keyboard is pressed (no need to press the Enter key too) ...

# use Tkinter for a console anykey function
# for Python3 use import tkinter as tk
# tested with Python 2.6.5  vegaseat

import Tkinter as tk

def anykey(prompt="Press any key to continue ... "):
    """
    waits until any key on the keyboard is pressed
    (use only in console programs)
    """
    def key(event):
        # quits all Tkinter programs, so watch out
        root.quit()
        return
    root = tk.Tk()
    print(prompt)
    root.bind_all('<Key>', key)
    # Tkinter window will not show
    root.withdraw()
    root.mainloop()

# run some console code
for x in range(100, 200, 10):
    print(x)

# now call anykey
anykey()

# do some more console stuff
for c in "hello":
    print(c)

anykey()

# do more code or allow exit

The next option would be to use a mouse click to continue a console program. Here we can't withdraw the root, but make it full screen and transparent instead. This way it won't show ...

# use Tkinter for a console mouse click function
# for Python3 use import tkinter as tk
# tested with Python 2.6.5  vegaseat

import Tkinter as tk

def mouseclick(prompt="Click the left mouse button to continue ... "):
    """
    waits until the left mouse button has been clicked
    (use only in console programs)
    """ …
Gribouillis commented: nice ! +3
TrustyTony commented: Interesting +2
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The pygame.mixer is a required argument in function
create_gui(app, mixer, sound_file)
where it is used in code line
track = mixer.Sound(sound_file)

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I would say Disney World. I always have a good time there.
However, a "cow tipping" excursion into Wisconsin sounds like fun too!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

It's time for a vacation!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Tkinter spin box is a nice input widget for numeric values. Let's take a closer look ...

# explore the Tkinter spin box
# similar to: http://effbot.org/tkinterbook/spinbox.htm
# tested with Python 3.1.2 and Tkinter 8.5  vegaseat

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

def click_sb1():
    """get value via textvariable"""
    s = "sb1 value = %s" % v.get()
    root.title(s)

def click_sb2():
    """get value directly"""
    s = "sb2 value = %s" % sb2.get()
    root.title(s)
 

root = tk.Tk()
root['bg'] = 'green'

v = tk.StringVar()

# goes from 0 to 10 in steps of 1 (default)
sb1 = tk.Spinbox(root, from_=0, to=10, textvariable=v, 
    command=click_sb1, width=40)
sb1.pack(padx=10, pady=5)

# goes from 0 to 10 in steps of 0.5
sb2 = tk.Spinbox(root, from_=0, to=10, increment=0.5,
    command=click_sb2)
sb2.pack(padx=10, pady=5)

# goes incremental 1 2 4 8 16
sb3 = tk.Spinbox(root, values=(1, 2, 4, 8, 16))
sb3.pack(padx=10, pady=5)

# goes incemental as specified by range()
# here from 10 to 100 in steps of 5
# list() needed for Python3
steps = list(range(10, 101, 5))
sb4 = tk.Spinbox(root, values=steps)
sb4.pack(padx=10, pady=5)

root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

...
My exercise says: Write a function wordPop that accepts a text and a length N and returns the list of all the words that are N letters long, sorted by their length.
...

According to this, the function has to return only words with the length N, so what is the sense of sorting them by length?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is a simple way to create a transparent image on your screen ...

# explore Tkinter transparency
# show image without root title or root border
# you have to add a way to exit, like mouse double click

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

def exit(event=None):
    root.destroy()

root = tk.Tk()
# only set x, y position of root
x = 200
y = 100
root.geometry("+%d+%d" % (x, y))

# use opacity alpha values from 0.0 to 1.0
# lower alpha is most transparent
# opacity/tranparency applies to image too
root.wm_attributes('-alpha', 0.7)  

# remove border from root window
root.overrideredirect(1)

# you can get sample image LAKE2.gif from
# http://www.daniweb.com/forums/post866067.html#post866067
photo = tk.PhotoImage(file="LAKE2.gif")

tk.Label(root, image=photo).pack()

# double click mouse on picture to exit
root.bind('<Double-1>', exit)

root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Pygame has some nice image processing available, here is an example ...

# experiments with module pygame
# free from: http://www.pygame.org/
# load, rotate, zoom and display an image
# tested with Python 3.1.2 and pygame 1.9.1 by vegaseat

import pygame as pg

# initialize pygame
pg.init()

# create a 640x480 black screen (black is the default)
screen = pg.display.set_mode((640, 480))

# pick an image you have (.bmp  .jpg  .png  .gif) in the 
# working folder, or use the full pathname
image_file = "Audi.jpg"

# load the image from a given file
image = pg.image.load(image_file).convert()

# this will rotate the image angle degrees counter clockwise
# and also zoom using the scale factor
angle = 25.5
scale = 1.5
image = pg.transform.rotozoom(image, angle, scale)
# optional window title
s = "%s rotated %s degrees and zoomed at %s" % \
    (image_file, angle, scale)
pg.display.set_caption(s)

# draw modified image, position the image ulc at x=5, y=-60
# negative y goes up
screen.blit(image, (5, -60))

# update the display window to actually show the image
pg.display.flip()

# run the event loop until
# the user clicks on the window corner x to exit
while True:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            raise SystemExit

Attached is the Audi.jpg image. IMHO the cutest car ever made. Run the program with the image and see what happens.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

In
threeRect = vl.get_rect()
where does v1 come from?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Another pygame mouse event code that checks if the mouse has been clicked inside or outside a given rectangle ...

# exploring module pygame
# draw a red rectangle on a white screen
# check if the mouse is clicked within the red rectangle
# tested with Python 3.1.2 and pygame 1.9.1  by vegaseat

import pygame as pg

# pygame uses (r, g, b) tuples for color
red = (255, 0, 0)
white = (255, 255, 255)

# window/screen width and height
screen_w = 450
screen_h = 450
screen = pg.display.set_mode((screen_w, screen_h))
# default background is black so fill it white
screen.fill(white)
pg.display.set_caption("click the mouse on the red rectangle ...")

# a rect object is set with (x1, y1, w, h)
# where (x1, y1) are the upper left corner coordinates
# w and h are the width and height of rect
rect = (130, 120, 180, 170)
x1, y1, w, h = rect
# calculate lower right corner coordinates (x2, y2) needed later
x2 = x1 + w
y2 = y1 + h
# pygame.draw.rect(Surface, color, Rect, width=0)
# if width is not given, then rectangle is filled
myrect = pg.draw.rect(screen, red, rect)

# update display
pg.display.flip()

# starting position
x, y = 0, 0

# event loop ...
running = True
while running:
    for event in pg.event.get():
        # quit when window corner x is clicked
        if event.type == pg.QUIT:
            running = False
        elif event.type == pg.MOUSEBUTTONDOWN:
            #print(event.pos)  # test
            x, y = event.pos

    # check if x …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A short piece of pygame code to show you a red square that follows the mouse click position ...

# exploring pygame mouse action
# let the red square follow the mouse click position
# tested with Python 2.6.5 and pygame 1.9.1  by vegaseat

import pygame as pg

# pygame uses (r, g, b) tuples for color
red = (255, 0, 0)
white = (255, 255, 255)

screen = pg.display.set_mode((500, 500))
pg.display.set_caption("click the mouse on the window ...")

# create a little red square
red_square = pg.Surface((30, 30))
red_square.fill(red)

# starting position
xy_position = (100, 100)

# set up the event loop
running = True
while running:
    event = pg.event.poll()
    keyinput = pg.key.get_pressed()
    # exit on corner 'x' click or escape key press
    if keyinput[pg.K_ESCAPE]:
        raise SystemExit
    elif event.type == pg.QUIT:
        running = False
    elif event.type == pg.MOUSEBUTTONDOWN:
        #print(event.pos)  # test
        xy_position = event.pos

    # this erases the old sreen
    screen.fill(white)
    # put the image on the screen at given position
    screen.blit(red_square, xy_position)
    # update screen
    pg.display.flip()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The SharpDevelop IDE is generally used for C# development on .Net framework (Windows) computers. Version 3.2 of this IDE can now be used directly with IronPython to create GUI programs in drag and drop fashion similar to the way that Microsoft's Visual languages use. IronPython 2.6.1 pretty well uses syntax compatible with Python 2.6. The GUI portion of the code looks very similar to a C# program. Well, here is an example of code created with the IDE. The IDE uses a solution approach with a program.py and an .resx XML file to compile the code to an .exe file via CLR. If you don't want the .exe file and its entourage, you can add a few extra lines (principally from program.py) to use the IronPython interpreter (ipy.exe) with the modified code. Here is an example of the modified code ...

# ip_sharp_listbox3.py
# Use the SharpDevelop 3.2 IDE from:
# http://www.icsharpcode.net/OpenSource/SD/Download/#SharpDevelop3x
# and IronPython 2.6.1 from:
# http://www.ironpython.org/
# to create a form with a listbox and 3 buttons
# load the listbox with names, sort the items
# clear the listbox items and show a selected item

# add these lines to the code created with SharpDevelop 3.2 IDE
# to run with the IronPython interpreter (ipy.exe)
import clr
clr.AddReference('System.Drawing')
clr.AddReference('System.Windows.Forms')

# SharpDevelop code starts here ...
import System.Drawing
import System.Windows.Forms

from System.Drawing import *
from System.Windows.Forms import *

class MainForm(Form):
	def __init__(self):
		self.InitializeComponent()
	
	def InitializeComponent(self):
		self._listBox1 = System.Windows.Forms.ListBox() …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

To get the external argument name of a function you can use dictionary globals() and id() ...

def the_function(arg):
    s = [key for key in globals() if id(globals()[key])==id(arg)][0]
    value = arg
    return "%s = %s" % (s, value)

my_long_variable_name = 'Some value'
print(the_function(my_long_variable_name))

"""Result >>>
my_long_variable_name = 'Some value'
"""
TrustyTony commented: Good code for debugging from my request +2
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The module easygui is used in education and is a simple set of Tkinter based popup boxes to interact with the user. Here is an example ...

# exploring easygui from:
# http://easygui.sourceforge.net/
# a simple but somewhat homely GUI toolit based on Tkinter
# using mostly popup boxes for user interaction

import easygui as eg

# create a choice box
msg ="What is your favorite flavor?"
title = "Ice Cream Survey"
choices = ["Vanilla", "Chocolate", "Strawberry", "Rocky Road"]
choice = eg.choicebox(msg, title, choices)

# send result to a message box
s = "One order of %s coming up!" % choice
eg.msgbox(msg=s, title='result', ok_button='OK', image=None, root=None)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If it wouldn't be for all those trees, I could see the forest.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Python31 not only included the Tkinter extension module ttk, but also the extension module tix. This module has plenty of extra features. Here is an example ...

# Tkx_ScrolledWindow1.py
# Tkinter extension module tix comes with version 3.1 of Python
# explore the tix.ScrolledWindow
# vertical and horizontal scroll bars appear as needed (automatic)
# see for instance C:/Python31/Lib/tkinter/tix.py for details

from tkinter import tix

app = tix.Tk()
app.title('exploring tix')

scr_win = tix.ScrolledWindow(app, width=200, height=300)
scr_win.pack(fill='both', expand=1)

sframe = scr_win.window
sframe.config(bg='brown')
s1 = 'Welcome to tkinter.tix, tkinter on steroids!'
s2 = '... Now included with Python31 ...'
for x in range(20):
    tix.Label(sframe, text=s1, bg='yellow').pack()
    tix.Label(sframe, text=s2, bg='white', fg='red').pack()

app.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is one solution ...

list1 = [
"['1426', '1095', '1094', '1093', '1092', '974', '869', '1572']\n",
"['1495', '1305', '1264', '1227', '1215', '1142', '1141', '1115']\n", 
"['1001', '997', '927', '904', '871', '776', '712', '612']\n", 
"['567', '538', '429', '415', '332', '326', '250', '247']\n", 
"['246', '245', '244', '155', '145', '133', '101']\n"]

list2 = []
for line in list1:
    # strip off the trailing '\n'
    line = line.rstrip()
    # use eval() to turn string line into list
    list2.append(eval(line))

import pprint
pprint.pprint(list2)

"""result >>>
[['1426', '1095', '1094', '1093', '1092', '974', '869', '1572'],
 ['1495', '1305', '1264', '1227', '1215', '1142', '1141', '1115'],
 ['1001', '997', '927', '904', '871', '776', '712', '612'],
 ['567', '538', '429', '415', '332', '326', '250', '247'],
 ['246', '245', '244', '155', '145', '133', '101']]

"""
modalgvr commented: Right the solution I was looking for. +0