Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tkinter - Why is there such a thing like bbox?

Now that I'm working more with tkinter Canvas I was wondering about the use of bbox.

For me I'm using bbox to get the coords of an element but the Canvas already have a method to return the coords of an item. So why did they invent something like bbox?

Comparing the official tcl description here:

bbox

pathName bbox tagOrId ?tagOrId tagOrId ...?

Returns a list with four elements giving an approximate bounding box for all the items named by the tagOrId arguments. The list has the form ``x1 y1 x2 y2'' such that the drawn areas of all the named elements are within the region bounded by x1 on the left, x2 on the right, y1 on the top, and y2 on the bottom. The return value may overestimate the actual bounding box by a few pixels. If no items match any of the tagOrId arguments or if the matching items have empty bounding boxes (i.e. they have nothing to display) then an empty string is returned.

coords

pathName coords tagOrId ?coordList?

Query or modify the coordinates that define an item. If no coordinates are specified, this command returns a list whose elements are the coordinates of the item named by tagOrId. If coordinates are specified, then they replace the current coordinates for the named item. If tagOrId refers to multiple items, then the first one in the display list is used.

I see the difference between these, but can't imaging in which case I would need a bbox instead of the coords? Can someone teach me a better understanding of this please?

like image 965
Thingamabobs Avatar asked Dec 31 '22 00:12

Thingamabobs


1 Answers

The difference is that with bbox() you can get the bounding box of a group of items (using a tag or 'all') while coords() returns the coordinates of the first item with given tag. Here is an example

import tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root)
canvas.pack()

i1 = canvas.create_rectangle(10, 10, 30, 50, tags='rect')
i2 = canvas.create_rectangle(60, 80, 70, 120, fill='red', tags='rect')

canvas.update_idletasks()
print('bbox', canvas.bbox('rect'))
print('coords', canvas.coords('rect'))

which gives

bbox (9, 9, 71, 121) 
coords [10.0, 10.0, 30.0, 50.0]

One of the typical use of bbox() is when you want to scroll a group of widgets using a canvas: The scrollregion of the canvas needs to be set to include all the canvas content so canvas.bbox('all') is quite useful. See for instance Adding a scrollbar to a group of widgets in Tkinter (in the onFrameConfigure() function).

like image 190
j_4321 Avatar answered Jan 15 '23 18:01

j_4321