惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
宝玉的分享
宝玉的分享
月光博客
月光博客
小众软件
小众软件
Jina AI
Jina AI
WordPress大学
WordPress大学
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
Tailwind CSS Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 【当耐特】
博客园 - 三生石上(FineUI控件)
博客园 - 司徒正美
大猫的无限游戏
大猫的无限游戏
The Cloudflare Blog
G
Google Developers Blog
M
MIT News - Artificial intelligence
N
Netflix TechBlog - Medium
云风的 BLOG
云风的 BLOG
MyScale Blog
MyScale Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
爱范儿
爱范儿
U
Unit 42
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Blog — PlanetScale
Blog — PlanetScale

Linux.org

PocketBeagle 2 TechLab - Part 1 Arduino Uno Q - LED Matrix - Rain Proxmox VE Series Part 5: Windows Virtual Machine PocketBeagle 2: Setup, Imaging, and Internet Access Orange Pi 6 Plus and Pimox 8.4.10 IRC is back on linux.org Arduino UNO Q: A Debian Linux Board for Headless Projects R36Pro Handheld with Linux ArkOS The Linux.org Story Python Series Part 25: Canvas Widget - Part 1: The Canvas and Its Drawable Objects Proxmox 04 - Linux Virtual Machine Banana Pi R4 (BPI-R4) - DHCP for Multiple Subnets Run Windows Apps on Linux with WinBoat Getting Started with the Radxa X5 SBC on Linux Python Series Part 23: Text Widget - Part 1 Proxmox VE Series Part 3: Basic Configuration Banana Pi R4 (BPI-R4) Python Series Part 23: Text Widget - Part 1 Proxmox VE Series Part 2: Installing Proxmox
Python Series Part 25: Canvas Widget - Part 2
invalid@example.com (Jarret B) · 2026-09-04 · via Linux.org

If you read the previous article, you should understand the Canvas Widget.

In this article, we will start with the different methods that are available to manipulate the objects on the Canvas.

Canvas Methods

There are many methods that can be used on Canvas widgets.

  • .addtag_above(newTag, tagOrId)
  • .addtag_below(newTag, tagOrID)

Now, we can add a tag to an item placed on a canvas. Keep in mind that each item, such as an oval, can have multiple tags. For instance, let's assume we place a rectangle, tagged as 'square', then an oval above it, tagged as 'oval', on a canvas. After we place each item, we can then use 'addtag_above' or 'addtag_below' as follows:

Code:

canvas.create_rectangle(200, 275, 350, 200, fill="purple",outline="blue",width=3,tag="square") canvas.create_oval(50, 225, 450, 300, fill="green",outline="yellow") canvas.addtag_above("oval1","square") canvas.addtag_below("square1","oval1")

In the 'addtag_above, we add the tag named 'oval1' to the object above the item tagged as 'square'. Notice that the oval has no initial tag name. Then, in the 'addtag_below', we can use the new tag name of 'oval1' we just created and give a second tag name for the rectangle named 'square1'. After this, we can use 'itemconfigure' to change the color and such using the new tag names.

  • .addtag_all(newTag)

Gives every item on the canvas a new or additional tag name.

  • .addtag_closest(newTag, x, y, halo=None, start=None)

If we need to find an object that is closest to the coordinates (x,y), then we can specify a new tag to place on the object closest to the coordinates. If you want to use the 'start' parameter, then you must specify a 'halo' parameter. The halo parameter is an area around the coordinate specified. If you set 'halo' to 1, then it will find the closest object no matter what the 'start' states. So, use a value for 'halo' that is the largest dimension of the canvas. The 'start' value is the ID of the object that will not be searched for as closest. Whatever value is in 'start', the closest object will have been placed on the canvas before it. To get the ID of an object, you draw the object and set it equal to a variable that will hold its ID:

Code:

ovalid = canvas.create_oval(50, 225, 450, 300, fill="green",outline="yellow")

So, to find the closest object and label it 'caught’ on the canvas, from the top left corner, that was placed on it before the oval was, you can do:

Code:

canvas.addtag_closest('caught',0,0,halo=400,start=ovalid)
  • .addtag_enclosed(newTag, x1, y1, x2, y2)

Here, you can add a tag to an object that is enveloped within the rectangle specified by the top left of a rectangle (x1,y1) and the bottom right (x2,y2). Remember that the item must be completely within the rectangle specified.

  • .addtag_overlapping(newTag, x1, y1, x2, y2)

You can specify a tag for any item that is partially inside the rectangle specified by (x1,y1)-(x2,y2).

  • .addtag_withtag(newTag, tagOrId)

If objects already have a specified tag or ID, then you can add a new tag to the object.

  • .bbox(tagOrId=None)

We can get the dimensions of an object by tag or ID. The values for (x1,y1)-(x2,y2) are placed into a tuple. The following is a good example to get the dimensions and then print them out:

Code:

dimensions=canvas.bbox("text1") for i in range(0,4): print (dimensions[i])[/code 
[LIST]
[*].canvasx(screenx, gridspacing=None)
[*].canvasy(screeny, gridspacing=None)
[/LIST]
 Gives the coordinates of the specified points. If the canvas is scrollable, then it can show that the points change as you scroll. An example of getting coordinates is: 
[code]canvasx0=canvas.canvasx(0) canvasy0=canvas.canvasy(0) canvasx1=canvas.canvasx(400) canvasy1=canvas.canvasy(300)
  • .coords(tagOrId, x0, y0, x1, y1, ..., xn, yn)

This method, in a way, works like '.bbox'. If no coordinates are given, then it returns a tuple containing the object specified by tag or ID. If multiple items have the same tag, then it gets the coordinates for the bottom-most object with the tag. If coordinates are given, then the object is moved to the given coordinates. In the following example, a rectangle is made, which we give the tag of 'square'. We then get the coordinates of the object using the tag and print out the tuple. Then, we move the object and get the coordinates again, this time using the ID:

Code:

squareid = canvas.create_rectangle(200, 200, 350, 275, fill="purple",outline="blue",width=3,tag="square") start=canvas.coords('square') for i in range(0,4): print (start[i]) canvas.coords(squareid,10,10,100,200) start=canvas.coords(squareid) for i in range(0,4): print (start[i])
  • .dchars(tagOrId, first=0, last=first)

If you have a text object, you can delete characters from the object. The first character is designated as '0', and the last character can be numbered or use 'END'. So, to delete characters from a text object tagged as 'text1' and starting at the sixth character (5) to the end (END), the command is:

Code:

canvas.dchars('text1',5,END)
  • .delete(tagOrId)

This method lets you remove an object by specifying the tag or ID of the object to be removed.

  • .dtag(tagOrId, tagToDelete)

Here, we can remove a tag from a specific object. In the following code, we can set a text object as 'textid' with a tag of 'text1' and an additional tag of 'text2'. We can then remove the 'text2' tag from the object:

Code:

canvas.dtag(textid,"text2")
  • .find_above(tagOrId)

With this method, we can find the highest object above the specified object. If no object is higher, then no result is given. Keep in mind that this represents items that are over another object and not higher on the canvas in the 'y' coordinate system.

  • .find_all()

We can now get a list of the items on the canvas from lowest to highest. If the canvas tag is 'canvas', we can see the ID of all the items on the canvas:

If I have three objects on the canvas, then the variable 'result' would contain '1 2 3'.

  • .find_below(tagOrId)

This is the same as 'find_above' except it is the lowest object under the designated one. If no other object is below the specified one, then nothing is returned.

  • .find_closest(x, y, halo=None, start=None)

We can find the closest object to 'x, y' coordinates and return the ID of the object. The 'halo' value is to increase the size of the point being used. The 'start' tag or ID will cause the highest object below the object. In the example, we will check the (x, y) coordinates of (200,350) on the canvas and use a halo of '10'. We will leave the 'start' object as 'None'.

Code:

result=canvas.find_closest(200,350,halo=10,start=None)
  • .find_enclosed(x1, y1, x2, y2)

Gets the object ID of every object within the square created by a box with a to left coordinate of (x1,y1) and a bottom-right corner of (x2,y2). In the below example, we set up a 'square' region with the coordinates of '(25,50)' and '(300,300)' to return the result in the variable 'objects':

Code:

objects=canvas.find_enclosed(25,50,300,350)
  • .find_overlapping(x1, y1, x2, y2)

With the 'find_overlapping' method, the values returned are any two or more objects that share a point within the coordinates given that make a square section.

  • .find_withtag(tagOrId)

Returns a list of objects that have the given 'tag' or 'ID' on the canvas. If we want to find a list of all objects with the tag 'oncanvas' and place the list in the variable 'results':

Code:

results=canvas.find_withtags("oncanvas")

If no matches are found, then no result is given.

  • .focus(tagOrId=None)

Gets or gives the current object focus. If you specify an object tag or ID, then the focus is moved to that object. Should there be more than one object, focus is given to the first on that allows an insertion cursor. If no tag or ID is given, then the ID is returned of the object with the current focus is returned.

Code:

canvas.focus(textid) result=canvas.focus()

Here, we give focus to the text object and then, in the second line, we find the ID of the text object, since it has focus, and place the ID in 'result'.

  • .gettags(tagOrId)

If you have the ID of a tag, then you can get the tag name for that ID. For instance, as with the '.focus' example, we can find the tag name with the code:

Code:

result=canvas.gettags(result)

Of course, having the two lines close together would not make sense since we just used the tag name in the first line, but if these lines were far apart, it would make more sense.

  • .icursor(tagOrId, index)

If we have an object that allows a text insertion cursor, we can place the cursor into the object and set the insertion point at the specified location. It is also possible to use the insertion point of 'end'. Even though the insertion cursor is placed at the specified point, the user cannot add text from the keyboard into a text object. To change text, you need to use '.itemconfigure' or '.insert'.

  • .index(tagOrId, specifier)

Here, you can get the position of the insertion character. The specifier option is:

  • tk.INSERT - returns the current position of the insertion cursor
  • tk.END - returns the position after the last character of the item
  • tk.SEL_FIRST - returns the position of the start of the current text selection. Tkinter will raise a tk.TclError exception if the text item does not currently contain the text selection
  • tk.SEL_LAST - to return the position after the current text selection, or raise tk.TclError if the item does not currently contain the selection
  • the form “@x,y” returns the character at the canvas coordinates (x, y). If those coordinates are above or to the left of the text item, the method returns 0; if the coordinates are to the right of or below the item, the method returns the index of the end of the item

There is an example below for this method in the '.select_adjust' method description.

If you do not need to use 'tk.' for your other commands, then you can remove them from the specifiers. Here, you can find more details about the insertion cursor.

  • .insert(tagOrId, specifier, text)

With the '.insert' method, we can insert text into an object after we set the insertion point. The specifier values are as follows:

  • tk.INSERT - returns the current position of the insertion cursor
  • tk.END - returns the position after the last character of the item
  • tk.SEL_FIRST - returns the position of the start of the current text selection. Tkinter will raise a tk.TclError exception if the text item does not currently contain the text selection
  • tk.SEL_LAST - to return the position after the current text selection, or raise tk.TclError if the item does not currently contain the selection

If we previously placed an insertion character into a text object, 'textid', on the canvas, we can add text, or 'INSERT', at the insertion point and add the text '-New text-':

Code:

canvas.insert(textid,INSERT,"-New text-")
  • .itemcget(tagOrId, option)

Returns the value of the specified option for an object. For example, we can get the content of the 'text' for a text object:

Code:

results = canvas.itemcget(textid,"text")

Any attribute of an object, you can retrieve with this method and then place the value returned into a variable or use directly in another object as needed.

  • .itemconfigure(tagOrId, option, …)

If you want to configure an option on an object, this is how you do it. Such as changing a color, text, etc. You just specify the 'tag; or 'ID' of the object, specify the option and set it equal to your new setting. Similar to creating a new object and specifying multiple options, you can do the same here:

Code:

ovalid = canvas.create_oval(50, 225, 450, 300, fill="green",outline="yellow",tag="oval1")
canvas.itemconfigure(ovalid,fill="blue", outline="red")

Now, these two lines will most likely be separated by other lines of code, but I will place them together to see the creation and change of the object. First, the oval object is created and is green with a yellow outline. We then change the oval, but only change the colors to a blue fill and red outline. You can change any of the options for the item.

  • .move(tagOrId, xAmount, yAmount)

Allows you to move an object left or right by the 'xAmount, and up or down by the 'yAmount'. Let's assume we create a square and then move it left 20 pixels and up 40 pixels:

Code:

squareid = canvas.create_rectangle(200, 200, 350, 275, fill="purple", outline="blue", width=3, tag="square")
canvas.move(squareid,-20,-40)
  • .postscript(option, ...)

There are a few options you can use:

  • colormode - Use 'color' for color output, 'gray' for gray-scale, or 'mono' for black and white
  • File - If supplied, names a file where the PostScript will be written. If not given, the output is returned as a string.
  • Height - How much of the Y-size of the canvas to print. The default is the entire visible height of the canvas
  • Rotate - If false, the page will be rendered in portrait orientation; if true, in landscape
  • X - Leftmost canvas coordinate of the area to print
  • Y - Topmost canvas coordinate of the area to print
  • Width - How much of the X size of the canvas to print, the default is the visible width

So, let's say we want to output the whole canvas as a PostScript format into a file '~/postscript.txt':

Code:

canvas.postscript(file="~/postscript.txt")

Conclusion

Again, this article was a little longer than expected, but the last article covering the Canvas Methods will be shorter. It will also conclude the information on the Canvas Widget. For now, get familiar with these methods and keep in mind that there is more to come in the next article.