[Tutor] Change the font size of the lines and rectangle on aTkinter Canvas

Michael Lange klappnase at freenet.de
Tue Jan 16 10:52:22 CET 2007


On Tue, 16 Jan 2007 00:33:20 -0000
"Alan Gauld" <alan.gauld at btinternet.com> wrote:

> 
> "Asrarahmed Kadri" <ajkadri at googlemail.com> wrote
> 
> > I want to provide with a functionality of changing the font size, in 
> > this
> > case the width of the lines.
> Its not really the font size. fonts only apply to text, its only
> the line width you want to change. However todo that I
> think the easiest way is just to elete the existing line
> (and maybe the whole graph) and redraw with the new
> parameters. Provideed the data has been precalculated
> then this should be a rapid operation.
> 

I am not sure if the OP meant to increase the graph elements according
to the font size, so the graph does not look tiny next to a huge font.

Anyway, there is no need to delete and recreate the items, just calculate
the new coordinates and pass them to Canvas.coords()

> 
> > Is it possible to do it dynamically; I mean the graph is
> > already drawn, now with a Menu, suppose I want to
> > provide the user with options of 50%, 100%
> > and 200% font size.
> 
> You will need to store the line thicknesses in variables
> so that the drawing routine can be parameter driven. Then
> simply delete the existing graph and redraw it with the
> new thickness - remember you may need to rescale
> your axis to cater for thicker/thinner lines.
> 

This is probably not necessary either, you can query the size of canvas elements
dynamically, use Canvas.bbox() to query width and height of rectangles or
Canvas.itemcget(item, 'width') and again Canvas.bbox() for line elements.

> If you are using a filled Rectangle rather than a real line
> (which is what I would actually expect to see in a bar chart)
> then obviously the line thickness simply involves setting
> the difference in the y coordinates appropriately.
> 

If you only want to be able to resize the graph elements into half and double size
it is probably easiest to use the Canvas.scale() method for this, like

>>> from Tkinter import *
>>> c=Canvas()
>>> c.pack(fill='both', expand=1)
>>> r = c.create_rectangle(20, 20, 70, 30, fill='red')
>>> c.scale(r, 20, 20, 2, 2)
>>> c.scale(r, 20, 20, 0.5, 0.5)

However, text, image and window items cannot be scaled.
If you want to "scale" text items, it might be the best to pre-define
e.g. three pixel-sized fonts, like

fonts = {'small':'helvetica -10', 'normal':'helvetica -12', 'big':'helvetica -14'}

and then provide a callback that will both change the font size for the
text elements and scale the graph elements (and the x- and y-axis).

I hope this helps

Michael





More information about the Tutor mailing list