[Tutor] Canvas rectangle filling

Abel Daniel abli@freemail.hu
Thu Jun 12 10:45:26 2003


Suresh  Kumar wrote:
> Hi,
> Iam using python/tkinter/pmw in windows.
> Most of graphics languages provides facility to fill the rectangcle with
> horizantal/vertical lines. I know that in tkinter we can fill the canvas
> rectangle's interior using "stipple". But my customer is expecting the
> rectangles to be filled with  diagnal/vertical/horizantal lines. Is
> there any direct way is available in tkinter/Pmw to fill the rectangle with
> lines?
> or i have to use "create_line" command explicitly?
Well, creating the lines invidually is an option, but i think it's a
rather poor one. You would have to figure out the endpoints of each
line, which might work for rectangles, but will get almost impossible
for circles, or arcs.
(Not to mention that you would be creating a lot of lines, which i guess
would impact performance.)

I think the best idea would be to use stipple with custom bitmaps. For
example the following xbm file will create diagonal lines:
----8<----
/* Created with The GIMP */
#define lines_width 16
#define lines_height 16
static unsigned char lines_bits[] = {
   0x11, 0x11, 0x22, 0x22, 0x44, 0x44, 0x88, 0x88, 0x11, 0x11, 0x22, 0x22,
   0x44, 0x44, 0x88, 0x88, 0x11, 0x11, 0x22, 0x22, 0x44, 0x44, 0x88, 0x88,
   0x11, 0x11, 0x22, 0x22, 0x44, 0x44, 0x88, 0x88 };
----8<-----
Copy-paste this into a file, call it 'lines.xbm', and use it like:
canvas.create_rectangle(100,100,150,150, stipple='@lines.xbm', fill='black')

There might be two problems:
1) path to the xbm files. If you put your xbm files somewhere else than
the current directory, I think you will have to use the full path, like:
... stipple='@/path/to/file.xbm' ...
Which might complicate the matters as you have to keep track of where
your xbm files are, and use the appropriate path.

2) creating the xbm files themselves. If you only need some options like
'diagonal lines, close the each other' or 'vertical lines, far apart'
you could create some xbm files, and only provide those. (Essentially
hardcoding thos patterns.) If you need more flexibility, like 'lines at
60 degrees angle, 2 pixels wide and 7 pixels apart' you will have to
generate xbm files on the fly. A way of pipeing the xbm data would come
handy in this case, but I don't know if such exists. You might have to
save the generated xbm data to be able to pass the filename to tkinter.
I think generating the xbm files on the fly will be pretty easy, as they
are simply black&white bitmaps.

According to
http://www.pythonware.com/library/tkinter/introduction/x2861-options.htm
which is describing the options of arc object:
"As of Tk 8.0p2, the stipple option is ignored on the Windows platform.
To draw stippled pieslices or chords, you have to create corresponding
polygons."

But I think that doesn't affect other objects. (I didn't test on Windows)

Abel Daniel