Extending Python/Tkinter

Richard Townsend richard at NOstarfighterSPAM.freeuk.com
Tue Mar 19 14:13:34 EST 2002


> I have a C++ class that draws maps that I've been assigned to extend
> into python.  The class uses X primitive calls (XDrawPoint, etc.) to
> do much of the work and I'm at a loss on how to integrate this as an
> extension to Python.  Initially I thought  I could get a drawable,
> display and graphics context from the Tk C API.  Then I saw that
> Tkinter is using the Tcl interpreter and not calling the Tk routines
> directly.  Now I'm lost.  I'm a newbie to Python/Tk/Tcl and hitting
> info overload from looking through so many books and web pages (sorry
> is this is a bad question).  I'm missing something crucial or this
> approach is half-baked or both.
>

Tkinter doesn't have an equivalent of XDrawPoint, but you could use PIL.

I wrote a simple application to display elevation data for the UK. It was
rather slow, but it did the job.

You need the following imports

import Image
import ImageDraw
import ImageTk

Here is my method that creates the image and copies it to a Tkinter Canvas
widget - perhaps you could adapt the concepts:

    def createImage(self):
        """Create an image containing the data from the file """

        m_file = open('uk_map.dat', 'rb')

        self.img = Image.new("RGB", (self.map_width, self.map_height))

        self.photo = ImageTk.PhotoImage(self.img)
        self.canvas.create_image(0, 0, anchor=NW, image=self.photo,
tags='img')
        self.canvas.resizescrollregion()

        draw = ImageDraw.Draw(self.img)

        # Fill image with the sea colour
        draw.rectangle((0, 0, self.map_width, self.map_height),
                       fill=self.colours[0])

        for y in range(0, self.map_height):
            for x in range(0, self.map_width):
                b1, b2 = m_file.read(2)
                elev = ord(b1) + 256 * ord(b2)

                if elev > 0:
                    draw.point((x, y), self.colours[elev])

            if y % 50 == 0:
                self.photo = ImageTk.PhotoImage(self.img)
                self.canvas.itemconfigure('img', image=self.photo)
                self.canvas.update()

        m_file.close()

        del draw

        self.photo = ImageTk.PhotoImage(self.img)
        self.canvas.itemconfigure('img', image=self.photo)
        self.canvas.update()


Hope that is of some use,
RT






More information about the Python-list mailing list