vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A simple way to display a list of lists/tuples as a table in your browser ...

# make_html_table.py
# create an html table from a data list

def make_html_table(mylist):
    """
    use a list of data tuples and create the html code
    of a html formatted table containing the data items
    """
    rows = ['<td>'+'</td><td>'.join(xx)+'</td>'+'\n' for xx in mylist]
    table = '<table border=2><tr>'
    table += '<tr>'.join(rows)
    table += '</tr></table>'
    return table

# a list of (name, age, weight) tuples (or lists)
# the first tuple is the header
data_list = [
('Name', 'Age', 'Weight'),
('Sarah Gellar', '26', '121'),
('Alec Baldwin', '47', '214'),
('Mandy Moore', '22', '135'),
('Matthew Goode', '29', '167'),
('Amanda Bynes', '19', '112'),
('James Kirk', '24', '175')
]

html_table = make_html_table(data_list)

print(html_table)  # test

# save as html file and show in your browser
with open('html_table.htm', 'w') as fout:
    fout.write(html_table)

You can use this simple code to show the above html file in your web browser ...

# use Python's webbrowser module to show an html code file 

import webbrowser

# open your web browser to run the html file
webbrowser.open('html_table.htm')
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Easy to overlook, random.choice() is usually used to pick an item from a list. However, it does apply to any sequence ...

import random

# pick a random letter out of a string
print(random.choice('abcdefg'))
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Milk anyone?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Yes, PyQT comes with the designer! See:
http://www.daniweb.com/forums/post1108430.html#post1108430

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can add this code to the end of the snippet code ...

print('-'*60)

# optional, count files with matching dates
date_name_list = []
for file in date_file_list:
    # extract just the filename
    folder, file_name = os.path.split(file[1])
    # convert date tuple to MM/DD/YYYY date format
    file_date = time.strftime("%m/%d/%y", file[0])
    date_name_list.append((file_date, file_name))

# contains date:count pairs
date_count_dict = {}
# contains date:[files] pairs
date_name_dict = {}
for date, name in date_name_list:
    # word_freq[word] = word_freq.get(word, 0) + 1
    date_count_dict[date] = date_count_dict.get(date, 0) +1
    date_name_dict.setdefault(date, []).append(name)

import pprint
print("Files with the same date:")
pprint.pprint(date_name_dict)
print('-'*60)
print("Same dates count:")
pprint.pprint(date_count_dict)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can use the Tkinter Entry() widget to enter a valid function_of_x string, evaluate it with eval(), and then plot it with VPython. Here is an example ...

"""tk_vp_plotting.py
using Tkinter to get the function of x input for a VPython plot
(console raw_input() does not work with VPython)
you can plot several functions, hence the random curve colors 
tested with Python27  by  vegaseat
"""

import Tkinter as tk
import visual.graph as vg
import random
from math import *

class MyApp(tk.Tk):
    def __init__(self, prompt):
        # the root will be self
        tk.Tk.__init__(self)
        self.title("Tkinter plotting with VPython")
        # set tk window x, y position below visual window
        self.geometry("+15+420")
        self.prompt = prompt
        self.v = tk.StringVar()
        # set some initial functionx string
        self.v.set("cos(x)")
        self.createWidgets()
        
    def visual_plot(self):
        # optionally make curve color random
        color_list = [vg.color.cyan, vg.color.yellow, vg.color.green]
        curve_color = random.choice(color_list)
        curve = vg.gcurve(color=curve_color)
        for x, fx in self.plot_data:
            curve.plot(pos=(x, fx))
    
    def get_data(self, functionx):
        plot_data = []
        # create a range of x values from 0 to 9 in steps of 0.1
        # this might have to be changed via user entry
        for x in vg.arange(0, 9.1, 0.1):
            # evaluate string function of x
            fx = eval(functionx)
            #print(x, fx)  # test
            plot_data.append((x, fx))
        return plot_data
    
    def createWidgets(self):
        self.label = tk.Label(self, text=self.prompt)
        self.label.grid(row=0, column=0, padx=10, pady=1)
        self.enter = tk.Entry(self, textvariable=self.v, bg='yellow')
        self.enter.grid(row=1, column=0, padx=10, pady=1)
        self.button = tk.Button(self, text="plot the function of x",
            command=self.action)
        self.button.grid(row=2, column=0, padx=10, pady=1)

    def action(self):
        # function of x string from entry widget
        functionx = self.v.get()
        self.plot_data = self.get_data(functionx)
        self.visual_plot() …
sneekula commented: without threading too +12
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you're not part of the solution, you're part of the precipitate.
-- Henry J. Tillman

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I think science has enjoyed an extraordinary success because it has such a limited and narrow realm in which to focus its efforts. Namely, the physical universe.
-- Ken Jenkins

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Research is what I'm doing when I don't know what I'm doing.
-- Wernher Von Braun (famous rocket scientist)

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

... oh yes, I remember owning an Osborne 'carry-on suitcase' computer. It was the first commercial portable computer made. Had that real tiny screen in the center.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

... you shout 'F1' instead of 'help'

skilly commented: funny +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Keywords are more basic for the Python code ...

# if you use a Python keyword for a variable name 
# you get an error message, your code will not run

from keyword import kwlist

print "A list of Python's keywords:"
for kw in kwlist:
    print kw
    
''' result for Python27 ...
A list of Python's keywords:
and
as
assert
break
class
continue
def
del
elif
else
except
exec
finally
for
from
global
if
import
in
is
lambda
not
or
pass
print
raise
return
try
while
with
yield

'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Please use code tags with your code to preserve the indentations. Otherwise the code is very difficult to read and not too many folks will help.

[code]
your Python code here

[/code]

Indentations are critical with Python to identify blocks of code. The common way is to use 4 spaces. Do not use tabs, they will screw you up sooner or later, because tabs are set to any number of spaces by individual editors. A mixture of tabs and spaces will make your code wrong.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Line if __name__ == '__main__': does not have to be used unless you want to use your program as a module and test it ...

# use if __name__ == '__main__': for testing a module
# allows the program to run or be an importable module
# __main__ is the name-space of the current program
# if a module is imported, the name-space changes to the name of the module

def function1():
    print('hello from function1')

# test the module
# this code block will be ignored if imported as a module
if __name__ == '__main__':
  function1()

Let's say you saved the above code as funk1.py, then you can import it into other programs ...

import funk1

# call the module function with the module name-space
funk1.function1()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Once again:

A Python package is a reference to the name of the folder containing a number of files. A library is the reference to a specific file, can be a .py file.

For instance in Python2 you use:
import Tkinter
this uses file Tkinter.py somewhere in your Lib folder.
Tkinter.py is a module.
Module names are case sensitive.

In Python3 this has changed to a package and you use:
import tkinter
this uses the files in a subfolder called tkinter in your Lib or Lib/site-packages folder.
Package subfolders have a file __init__.py in them.
Python will look at this file first.
Package names are also case sensitive.
By convention package names are in lower case.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Ah, the power of the eval() function. With this tiny calculator you can easily find the square-root as long as you remember that the square-root of x is simply x to the power 1/2.

So, to find the square-root of 2 simply enter 2**0.5=

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

... you wear black rimmed glasses that have been taped with white hospital tape, and your shirt has a pocket protector with about twenty pens sticking out of it.

The perfect stereotype! :)

vedro-compota commented: +++++++++++ +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Since we are talking about plotting, often overlooked is VPython, that has quite a nice plotting feature. It is fairly simple to use, here is an example ...

""" vp_plot_bars1.py

use VPython to draw a bar chart

module visual (aka VPython) comes in Windows, Linux and Mac flavors

Windows download website:
http://vpython.org/contents/download_windows.html
pick the download for your version of Python
I used installer VPython-Win-Py2.7-5.41.exe
"""

import visual.graph as vg

# set up the plot display
# if xmax, xmin, ymax, ymin are not specified, 
# then the default is auto scale
myplot = vg.gdisplay(x=80, y=50, width=680, height=350,
    title = 'widgets sold each day',
    xtitle='day', 
    ytitle='widgets sold',
    foreground=vg.color.black,
    background=vg.color.white)

draw_bars = vg.gvbars(delta=0.5, color=vg.color.red)

# list of data to be graphed
data = [30, 45, 80, 150, 220, 180, 110, 75, 50, 35, 20, 15, 10, 10]

for day, units in enumerate(data):
    draw_bars.plot(pos=(day+1, units))
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The popular plotting module matplotlib works very well within Tkinter ...

"""
embedding module matplotlib in a Tkinter GUI application
tested with Python 2.7 and matplotlib 1.0.1
"""

import matplotlib
matplotlib.use('TkAgg')

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.backends.backend_tkagg import NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import math
import Tkinter as tk

root = tk.Tk()
root.wm_title("Embedding matplotlib in Tkinter")


fig = Figure(figsize=(6, 5), dpi=100)
myplot = fig.add_subplot(111)

# brew up a simple sample plot
# create a list of floating point numbers
# this will be the x-axis data
float_list = [x/100.0 for x in range(300)]
# now create a list of sine values
# this will be the y-axis data
sine_list = [math.sin(2*math.pi*y) for y in float_list]
# optional labels
myplot.set_xlabel('x')
myplot.set_ylabel('y = sin(x)')
# then plot the two list's data in red
myplot.plot(float_list, sine_list, 'r')


# create a tk.DrawingArea
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.show()
canvas.get_tk_widget().pack(side='top', fill='both', expand=1)

toolbar = NavigationToolbar2TkAgg( canvas, root )
toolbar.update()
canvas._tkcanvas.pack(side='top', fill='both', expand=1)

root.mainloop()
Ene Uran commented: thanks +13
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

To allow for comparisons, here is the URL image viewer using Tkinter and PIL ...

"""
view an image with Python using the Tkinter GUI toolkit
get the image from a webpage URL

note: urllib2 has changed in Python3

tested with Python 2.7 and PIL 1.1.7
"""

import Tkinter as tk
from PIL import ImageTk
# Python2
import urllib2

root = tk.Tk()
root.title("Tkinter URL Image Viewer")

# get a URL based image from the internet
# the url was very long so I split it in half
part1 = "http://uploads.neatorama.com/wp-content/"
part2 = "uploads/2011/05/cogtrain-500x688.jpg"
url = part1 + part2
picture = urllib2.build_opener().open(url).read()

# use PIL to convert to a format Tkinter can handle
image_tk = ImageTk.PhotoImage(data=picture)

# put the image on a typical widget
label = tk.Label(root, image=image_tk)
label.pack(padx=5, pady=5)

root.mainloop()
ZZucker commented: great code, thank you +8
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You might want to check the example of a simple threading decorator here:
http://www.daniweb.com/software-development/python/threads/20774/1576229#post1576229

It will show you that time.sleep() can run in the background.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Questions about threading come up many times on the forum, so here some help ...

# running a function in the background with threading
# apply threading to a function with a function decorator
# without the threading decorator the function counter2
# would tick off first, then the other prints would show

import time
import threading

def background(f):
    """
    a threading decorator
    use @background above the function you want to thread
    (run in the background)
    """
    def bg_f(*a, **kw):
        threading.Thread(target=f, args=a, kwargs=kw).start()
    return bg_f

@background
def counter2(n):
    """show the count every second"""
    for k in range(n):
        print("counting %d" % k)
        time.sleep(1)

# start the counter
counter2(7)
time.sleep(0.9)
print('hello')   # prints hello, before counter prints 1
time.sleep(3)
print('world')   # prints world, before counter prints 4

''' result ...
counting 0
hello
counting 1
counting 2
counting 3
world
counting 4
counting 5
counting 6
'''
HiHe commented: now that's easy +5
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I coded the above Jython Image Viewer program with Python27 and PyQt, a little bit more complex ...

"""
view an image with Python using the PyQt GUI toolkit
get the image from a webpage URL or any image file

note: urllib2 has changed in Python3

tested with Python27 and PyQt48
"""

from PyQt4.QtCore import *
from PyQt4.QtGui import *
# Python2
import urllib2

app = QApplication([])
# create the window/frame
win = QWidget()
win.setGeometry(100, 50, 500, 688)
win.setWindowTitle("PyQt Image Viewer")

# get a URL based image from the internet
# the url was very long so I split it in half
part1 = "http://uploads.neatorama.com/wp-content/"
part2 = "uploads/2011/05/cogtrain-500x688.jpg"
url = part1 + part2
picture = urllib2.build_opener().open(url).read()

# save the image as a file
fname = "cogtrain-500x688.jpg"
fout = open(fname, "wb")
fout.write(picture)
fout.close()

# load the picture back in a form PyQt can process
image = QPixmap(fname)

# use a label to display the image in
label = QLabel(win)
label.setPixmap(image)

win.show()

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

Some more explorations with Jython ...

"""
view an image with Jython using the Java swing GUI toolkit
get the image from a webpage URL or any image file
tested with jython2.5.2  by  vegaseat
"""

from pawt import swing
from java import net

def view_image(image):
    frame = swing.JFrame("Jython Image Viewer") 
    # allows frame corner x to exit properly
    frame.defaultCloseOperation = swing.JFrame.EXIT_ON_CLOSE
    frame.visible = True
    frame.setSize(500, 688)
    # show the image in a label
    frame.getContentPane().add(swing.JLabel(swing.ImageIcon(image)))
    frame.show()

# get a URL based image from the internet
# the url was very long so I split it in half
part1 = "http://uploads.neatorama.com/wp-content/"
part2 = "uploads/2011/05/cogtrain-500x688.jpg"
url = part1 + part2
# now that is sweet ...
image = net.URL(url)
view_image(image)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I am still not quite sure what you want, but it looks like you have the right idea with nested loops. This might give you a hint how to proceed ...

q = [1, 3, -6, 0]

qq = []
for ix, x in enumerate(q):
    for iy, y in enumerate(q):
        if ix != iy:
            print( x, y)  # test
            qq.append(x - y)

print('-'*20)
print(q)
print(qq)

''' my result ...
(1, 3)
(1, -6)
(1, 0)
(3, 1)
(3, -6)
(3, 0)
(-6, 1)
(-6, 3)
(-6, 0)
(0, 1)
(0, 3)
(0, -6)
--------------------
[1, 3, -6, 0]
[-2, 7, 1, 2, 9, 3, -7, -9, -6, -1, -3, 6]
'''
bumsfeld commented: good hint +11
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just for kicks, here is a manual random number generator ...

import time

def get_random_number():
    """a manual random number generator"""
    start = time.time()  
    #print(start)  # test
    raw_input("Press Enter ...")
    #print(time.time())  # test
    # returns a number from 0 to 99
    return int((time.time() - start) * 1000) % 100
    
random_number = get_random_number()
print(random_number)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Most of the time when they talk about build it means build from source code. OS specific binary installer files take care of that for you.

Enjoy exploring Python, a powerful language that can be a fun.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can concatenate the two words into a search word and use module re to help you. Something along this line ...

import re

text = "The pleasant peasantry likes to eat pheasant!"

find = 'as' + 'ant'

for word in text.split():
    found = re.search(find, word)
    if found:
       print("found '%s' in %s" % (found.group(0), word)) 

'''
found 'asant' in pleasant
found 'asant' in peasantry
found 'asant' in pheasant!
'''

Also Python has a build-in function find(). I an sure you can apply this hint to your problem.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You already have the Windows binary self-installer, so it should work right out of the box.

Simply run one of the example programs from DaniWeb:
http://www.daniweb.com/software-development/python/threads/191210/1525722#post1525722
or something that came with the installation, like:
C:\Python27\Lib\site-packages\PyQt4\examples\demos\textedit\textedit.pyw

The qscintilla2.dll is also already installed.

Download your Eric4 (Eric5 if you have Python32) zipped file and unzip it. Run install.py from something like IDLE, Eric4 should install into your Python27 folder. It will be in the Lib\site-packages folder. It leaves a batch file in the Python27 folder. You use eric4.bat to get going.

Since I have Python32, I downloaded eric5-5.1.3.zip from
http://eric-ide.python-projects.org/eric-download.html
Installed it on my Windows7 machine. I am impressed. Eric does not have the input() problem like Editra has.

I real nimble Python editor for Windows is PyScripter. It is written in Delphi and you simply download the .exe file.
If you have several version of Python intalled, it might have problems choosing.

ZZucker commented: just what I needed +8
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you wan to get numeric input, optionally within a range of values, you can use the Tkinter GUI toolkit (comes with your Python installation) and its small pop-up dialogs in a console program ...

# use Tkinter's simple dialogs (pop-up) to ask for input
# minvalue and maxvalue are optional

try:
    # for Python2
    import Tkinter as tk
    import tkSimpleDialog as tksd
except ImportError:
    # for Python3
    import tkinter as tk
    import tkinter.simpledialog as tksd

root = tk.Tk()
# show input dialogs without the Tkinter window
root.withdraw()

# if a non-numeric value is entered, will prompt again
price = tksd.askfloat("Price", "Enter the price of the item:")
print(price)
# use askfloat or askinteger (whole items only)
quantity = tksd.askinteger("Quantity", "Number of items needed:",
    minvalue=1, maxvalue=1000)
print(quantity)

result = "Total cost is %0.2f" % (price*quantity)
print(result)

# you could even use askstring() to display the result
sf = "%0.2f" % (price*quantity)
tksd.askstring("Result", "Total cost is:", initialvalue=sf)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A dictionary coordinate tuple still has the row column problem.
There is a code snippet about that here on DaniWeb.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Search for your answer first!

If you're having a problem, chances are good that someone else has had the same problem. Please search the forum for existing answers before starting a new thread. Nothing is more irritating to a long time member than to answer the same question for the umpteenth time because someone didn't use the forum's search feature.

Don't resurrect old threads!

Inevitably, if you use the search feature you'll stumble upon an interesting thread that you think you can add to. Resist the temptation to post until you've looked at the post date for the most recent post in that thread. It's possible that the thread is years old and you have no business bumping it to the top of the list. A thread is considered old after two months.

Let dead threads lie, don't post in them!

Create a meaningful title!

So you've searched and haven't found anything that fits your problem? Great! We can help, but you need to peak our interest with a thread title that briefly describes your problem. Many members browse the topic list and choose which threads to post in only by the title. Oh, and for future reference, "HELP!!!11" or any variation thereof does not describe your problem.

If you don't know what the problem is, create a title that tells us what you're trying to do. For example: "Convert a string to an integer".

Describe your problem clearly and fully!

griswolf commented: Thank you! +11
Gribouillis commented: great +13
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Hey Henri, very nice widget tester for Pyside (for PyQt change imports). I just wanted to know if the list box would add a scroll-bar automatically for a long list. It does ...

# test PySide widgets
# load a list box

from PySide.QtCore import *
from PySide.QtGui import *

app = QApplication([])

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

# Fnames.txt is a file of names, one each line
with open("Fnames.txt", "r") as fin:
    # remove trailing newline characters
    name_list = [name.strip() for name in fin]

# automatically adds vertical scrollbar for this long list
listbox = QListWidget()
listbox.addItems(name_list)

listbox.show()

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

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

I'm assuming that the aim here is to make Java developers aware of the JVM port of Python programming language and the goodies which it brings with it. However, those thinking of making a transition from CPython to Jython in hope of a better GC and threading, please make sure you read the "differences between CPython and Jython" page (not sure how updated that page is, but worth a read).

As a side note, "Grinder", the load testing framework uses Jython as its scripting language. :-)

Looks like that article is from 2007 or earlier, a little outdated as Jython has made many improvements. Using Jython as a scripting language for Java programs is however not a bad idea.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Hello, I am vegaseat, the goofy moderator from the Python forum of DaniWeb. I wanted to know if anyone in the Java forum has played around with Java based Python, also known as Jython.

Jython uses easy to learn Python syntax and can use the Java libraries. To make a short story long, here is an example ...

""" jy_List_99BoB2.py
create the full lyrics of the '99 bottle of beer' song
and show in a Jython (Java based Python) scrollable list box

Download file jython_installer-2.5.2.jar 
from http://www.jython.org/downloads.html

On Windows just double click the .jar file
and Java will install the Jython program
into a directory called jython2.5.2

to this .py file on Windows use:  
Jython.bat jy_List_99BoB2.py

tested with jython2.5.2  by  vegaseat
"""

# import needed Java libraries
# swing is the Java GUI toolkit
from javax.swing import *
from java.awt import Color

# creates all lines of '99 bottles of beer' lyrics
# using some sensible slicing
list_99bob = []
bottle = " %s bottle"
beer = "s of beer on the wall!"
take = "! Take one down, pass it around,"
for k in range(99, 0, -1):
    s1 = ((bottle % k + beer[k==1:])*2)[:-13]
    s2 = bottle % (k-1 or "No")
    s3 = beer[k==2:-1] + "!"
    #print(s1 + take + s2 + s3  # test)
    list_99bob.append(s1 + take + s2 + s3)

frame = JFrame('99 Bottles of Beer song')
# allows frame corner x to exit properly
frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
frame.setLocation(100, 150)
frame.size = (400, …
peter_budo commented: Nice sample vegaseat ;) +16
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I think woooee's approach is clearer. The extra close() may be too easy to miss.

I agree! I think the OP wanted to explore the fact that can open two files on the same 'with' line.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This would be the basic experiment to set up a functioning analog clock with the Tkinter GUI toolkit ...

# explore a Tkinter analog clock
# using Canvas(), canvas line and Spinbox()

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

def click_hour():
    h = sb_hour.get()
    size = int(cv['width'])
    # get the spinbox value
    h = int(sb_hour.get())
    # set the line coordinates for hour hand
    # moves 30 degrees per hour (360/12)
    degrees = h * 30 
    # angle needs to be in radians
    angle = degrees*math.pi*2/360
    # center coordinates cx, cy
    cx = size/2
    cy = size/2
    # find proper endpoint coordinates for the line
    # multiplier of 0.32 makes hour hand shortest
    x = cx + size*math.sin(angle)*0.32
    y = cy - size*math.cos(angle)*0.32
    cv.coords('hour', (cx, cy, x, y))

def click_minute():
    size = int(cv['width'])
    # get the spinbox value
    m = int(sb_minute.get())
    # set the line coordinates for minute hand
    # moves 6 degrees per minute (360/60)
    degrees = m * 6
    # angle needs to be in radians
    angle = degrees*math.pi*2/360
    # center coordinates cx, cy
    cx = size/2
    cy = size/2
    # find proper endpoint coordinates for the line
    x = cx + size*math.sin(angle)*0.40
    y = cy - size*math.cos(angle)*0.40
    cv.coords('minute', (cx, cy, x, y))

def click_second():
    size = int(cv['width'])
    # get the spinbox value
    s = int(sb_second.get())
    # set the line coordinates for second hand
    # moves 6 degrees per second (360/60)
    degrees = s * 6 …
Ene Uran commented: nice conclusion +13
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I show this Tkinter code because it has a nice approach to OOP (Object Oriented Programming) and some basic trigonometric calculations to make an analog clock. I added enough comments to help you along ...

# a Tkinter analog clock experiment
# modified/corrected code from: 
# http://stackoverflow.com/questions/6161816/
# tested with Python27 and Python32  by vegaseat

import time
from math import cos, sin, pi
try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

class MyApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        # the root will be self 
        tk.Tk.__init__(self, *args, **kwargs)

        # used in hand calculations
        self.size=300

        self.title("Analog Clock")
        self.cv = tk.Canvas(self, width=320, height=320, bg='yellow', 
                           relief='raised', border=10)
        self.cv.pack()

        # these will be the clock hands
        # correct lines will be drawn during update_clock()
        self.cv.create_line(0,0,0,0, fill='black', tags='hour', 
                            arrow='last')
        self.cv.create_line(0,0,0,0, fill='blue', tags='minute', 
                            arrow='last')
        self.cv.create_line(0,0,0,0, fill='red', tags='second')

        # create at least 4 hour labels
        # you could make it all 12
        tk.Label(self, text="12", bg='yellow').place(x=160, y=13)
        tk.Label(self, text="6", bg='yellow').place(x=160, y=303)
        tk.Label(self, text="3", bg='yellow').place(x=310, y=160)
        tk.Label(self, text="9", bg='yellow').place(x=11, y=160)

        # optional date/time label
        self.time_label = tk.Label(self, text="")
        self.time_label.pack()

        # get the clock updated every second
        self.update_clock()

    def update_clock(self):
        self.time_label['text'] = time.ctime()
        
        # get present time tuple
        s = time.localtime()[5]
        m = time.localtime()[4]
        h = time.localtime()[3]

        # now on to some basic sin/cos trigonometry
        # to set the line coordinates for second hand
        # moves 6 degrees per second (360/60)
        degrees = s * 6
        # angle needs to be in radians
        angle = degrees*pi*2/360
        # center coordinates cx, cy
        cx …
Ene Uran commented: was looking for that +13
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Why don't cannibals eat clowns?
They taste funny!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Something like this I recommend a QGridLayout() ...

# explore multiple QFrame() in a QGridLayout()

from PySide.QtCore import *
from PySide.QtGui import *

class FrameTester(QWidget):
    def __init__(self, title, width, height, parent=None):
        # create the window (this will be instance self)
        QWidget.__init__(self, parent)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(100, 150, width, height)
        self.setWindowTitle(title)
        self.make_frame()
    
    def make_frame(self):
        frame1 = QFrame(self)
        frame1.setLineWidth(3)
        frame1.setFrameStyle(QFrame.Box|QFrame.Sunken)
        
        frame2 = QFrame(self)
        frame2.setLineWidth(3)
        frame2.setFrameStyle(QFrame.Box|QFrame.Sunken)        

        frame3 = QFrame(self)
        frame3.setLineWidth(3)
        frame3.setFrameStyle(QFrame.Box|QFrame.Sunken)
        
        grid = QGridLayout()
        grid.setSpacing(10)
        # addWidget(QWidget, row, column, rowSpan, columnSpan)
        # span 2 rows and 1 column each
        grid.addWidget(frame1, 1, 1, 2, 1)
        grid.addWidget(frame2, 1, 2, 2, 1)
        # span 1 row and 2 columns
        # note that you occupy row 3 now
        grid.addWidget(frame3, 3, 1, 1, 2)
       
        self.setLayout(grid)
    

# create the Qt Application
app = QApplication([])

title = "3 frames in a grid layout"
width = 800
height = 600
tester = FrameTester(title, width, height)
tester.show()

# run the main Qt event loop
app.exec_()

Again, I don't know where you are picking up your outdated coding style, seems from the very beginning of PyQT. It makes it hard for normal mortals to follow and help you.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

... you actually understand a news story without seeing a video about it.

GrimJack commented: heh, heh! +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

"A rich man is nothing but a poor man with money."
-- W. C. Fields

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

woooee is on to something, in your case you need to close the file before you can read it ...

text = "aim low and reach it"

fname = "test7.txt"

with open(fname, 'w') as foutp, open(fname, 'r') as finp:
    # write text to file
    foutp.write(text)
    # need to close the outp file so you can read it
    foutp.close()
    # read text from file
    mytext = finp.read()
    #print(foutp, finp)  # test

print("to file --> %s" % text)
print('-'*30)
print("from file --> %s" % mytext)

""" my result -->
to file --> aim low and reach it
------------------------------
from file -->  aim low and reach it 
"""
HiHe commented: that explains it +5
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you just have a Windows OS and Python version less than 3.0, you can use a program called py2exe. Here is the poop ...

"""
Py2ExeConSetup.py

Py2Exe (version 6.6 and higher) setup file for a console programs.
Creates a single .exe file.

Simply add this file into the same folder with the source file.
Change your source filename at the bottom to whatever you called your 
code file.  Now run Py2ExeConSetup.py ...

Two subfolders will be created called build and dist.
The build folder is for info only and can be deleted.
Distribute whatever is in the dist folder.
The dist folder contains your .exe file, any data files you specified
in "data_files =", MSVCR71.dll (maybe) and w9xpopen.exe

Your .exe file contains your code as . pyo optimized byte code files, 
all needed modules and the Python interpreter (as a Pythonxx.dll).
MSVCR71.dll can be distributed, but is often already in the system32 
folder or the C:\Windows\SysWOW64 folder on Windows7 (64bit). 
w9xpopen.exe is needed for os.popen() only, can be deleted otherwise.
vegaseat  05may2009
"""

from distutils.core import setup
import py2exe
import sys

sys.argv.append("py2exe")
sys.argv.append("-q")

setup(
  options = {"py2exe": {"compressed": 1,
                        "optimize": 2,
                        "ascii": 1,
                        "bundle_files": 1}},
  zipfile = None,
  # to add .dll or image files use list of filenames
  # these files are added to the dir containing the exe file
  #data_files = [('./images/red.jpg'), ('./images/blue.jpg')],
  # replace 'DateTime1.py' with your own code filename
  # (replace console with windows for a windows program)
  console = [{"script": 'DateTime1.py'}]
)

For …

bumsfeld commented: works well +11
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

For an example see:
[url]http://www.daniweb.com/software-development/python/threads/191210/1556772#post1556772[/url]

Note:
Programs like py2exe and cxfreeze simply package/combine necessary things (like code and interpreter) together and then unpackage it later to run on the users machine.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Italians have the best looking sports cars. Can they handle sharp turns?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A Chevy Impala doesn't even look like a sports car. It may be a heavy muscle car, but I would hate to spin it around some tight curves at high speed.

Now the Chevy Corvette is a muscle car and at least looks very sporty.

Portgas D. Ace commented: Perhaps if you can't drive. Don't comment. +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you want integer keys, try this ...

# dictionary comprehension needs Python27 or higher

text = """\
1\thello
2\ttest
"""

fname = "mytest.txt"
with open(fname, "w") as fout:
    fout.write(text)

with open(fname, "r") as fin:
    d = {int(x.strip().split('\t')[0]):x.strip().split('\t')[1] for x in fin}

print(d)  # {1: 'hello', 2: 'test'}
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Something simple, but handy at times ...

# convert an integer number to its binary representation
# and pad the result with a specified number of leading zeros
# tested with Python27 and Python32  by  vegaseat

def int2binpad(num, bits=4):
    """
    returns the binary of integer num, using bits
    number of digits, will pad with leading zeros
    """
    bs = ''
    for x in range(0, bits):
        if 2**x == 2**x & num:
            bs = '1' + bs
        else:
            bs = '0' + bs
    return bs

# testing ...
if __name__ == '__main__':
    print(int2binpad(255, 12))  # 000011111111
    print(int2binpad(254, 12))  # 000011111110
    print(int2binpad(76, 8))    # 01001100
    print(int2binpad(3))        # 0011