portable fortune program

J.Jacob joost_jacob at hotmail.com
Tue Apr 30 15:51:12 EDT 2002


Here is the GUI version.  It has menu options for a new fortune and
for copying to the system clipboard.  The whole thing is 104 lines of
source code.

Usage:
Put fw.py and your 'allfortunes' file somewhere in your sys.path.  The
format of the allfortunes file should be like the variable called
modulequotes in fw.py; modulequotes is used if it cannot find the
allfortunes file.
Now do:
python -c "import fw; fw.run()"

It should be portable and backwards compatible to python version
1.5.2, please let me know if it does not work with your python
installation.

Joost Jacob
www.liacs.nl/home/jjacob/

I like work ... I can sit and watch it for hours.


--------------------  fw.py  --------------------------------------

modulequotes = """At the end of every pot of gold there's a rainbow
%
To a three year old with a hammer, everything looks like a nail
%
"""

from Tkinter import *
import string, random, os, StringIO

quoteslist = []

def getQuote():
    """
    Return a quote <string> from file allfortunes,
    assume the file allfortunes is located in the same
    directory as this module."""
    if not quoteslist:
        try:
            datafile = os.path.join(
              os.path.dirname(__import__(__name__).__file__),
              'allfortunes' )
            quotesfile = open(datafile)
        except IOError:
            quotesfile = StringIO.StringIO(modulequotes)
        quote = ''
        for s in quotesfile.readlines():
            if s[0] == '%':
                if quote:
                    quoteslist.append(quote)
                    quote = ''
            else: quote = quote + s
        if quote: quoteslist.append(quote)
    return random.choice(quoteslist)


class TextMap(Frame):
    def __init__(self, parent=None, height=25, width=80):
        Frame.__init__(self, parent)
        self.width = width
        self.height = height
        self.pack()
        self.text = Text(self, wrap='none', relief=SUNKEN,
            font=('courier',10,'normal'),
            height=height, width=width)
        self.text.pack(side=LEFT, fill=NONE)
        self.text.config(state=DISABLED)
    def resize(self, height=None, width=None):
        if height:
            self.height = height
            self.text.config(height=height)
        if width:
            self.width = width
            self.text.config(width=width)
    def settext(self, textstr=''):
        self.text.config(state=NORMAL)
        self.text.delete('1.0', END)
        self.text.insert('1.0', textstr)
        self.text.update()
        self.text.config(state=DISABLED)
    def clear(self):
        self.text.config(state=NORMAL)
        self.text.delete('1.0', END)        # delete current text
        self.text.update()
        self.text.config(state=DISABLED)


class FortuneWindow:
    def showQuote(self): 
        self.root = Tk()
        self.root.title('Fortune')
        # add menu
        top=Menu(self.root)
        self.root.config(menu=top)
        top.add_command(label='Next', underline=0,
          command=lambda self=self: self._onNew())
        top.add_command(label='Copy', underline=0,
          command=lambda self=self: self._onCopy())
        # add fortune in textmap widget
        self.quote = getQuote()
        self._getDimensions()
        self.textmap = TextMap(height=self.height, width=self.width)
        self.textmap.settext(textstr=self.quote)
        # catch events
        self.root.mainloop()
    def _getDimensions(self):
        self.width = 0
        self.height = 0
        for s in string.split(self.quote, '\n'):
            self.height = self.height + 1
            if len(s) > self.width: self.width = len(s)
        if self.width == 0: self.width = 10
        if self.height == 0: self.height = 2
    def _onCopy(self):
        self.root.clipboard_clear()
        self.root.clipboard_append(self.quote)
    def _onNew(self):
        self.quote = getQuote()
        self._getDimensions()
        self.textmap.resize(width=self.width, height=self.height)
        self.textmap.clear()
        self.textmap.settext(textstr=self.quote)

def run():
    FortuneWindow().showQuote()



More information about the Python-list mailing list