TheDude
TheDude

Reputation: 55

Get items on canvas

Im working on a GUI for a board game. So I made some objects on the Canvas and I know they are somehow saved as integers because if I create it, it returns the int and if I canvas.delete(i) it gets removed. Summed up I have a mxn board and the squares are $i\in {1,__,m*n}$. How can I configure the cells now, by only knowing the integers? For all squares I set the tag: 'cells', therefore I can get the integers and change stuff:

items = canvas.find_withtag('cells')
canvas.itemconfig('cells', ...)

Do I have to set the (i,j) as a tag when I create the squares? Thanks for reading and good evening.

Upvotes: 0

Views: 3158

Answers (1)

Sens4
Sens4

Reputation: 665

I don't really often use Canvas quite often but this should be a workaround for what you have asking for:

import tkinter as tk

# Defining all of your constants
width = 10
height = 10
spacing = 2

countX = 20
countY = 10

# Dictionary which will contains all rectangles
_objects = {}

# Creating the window
root = tk.Tk()
root.geometry("200x100")
canvas = tk.Canvas(root, width = 200, height = 100, bg = "white")
canvas.pack()

# Creating all fields and naming than like coordinates
for y in range(countY):
    for x in range(countX):
        _objects["{0}/{1}".format(x,y)] = canvas.create_rectangle(0+(x*width),
                                                               0+(y*height),
                                                               width+(x*width) - spacing,
                                                               height+(y*height) - spacing)

# Call a ractangle [X/Y]
canvas.itemconfig(_objects["0/2"], fill = "red")
canvas.itemconfig(_objects["0/9"], fill = "yellow")
canvas.itemconfig(_objects["19/9"], fill = "green")

print(_objects)
root.mainloop()

So the idea is to use a simple Dictionary where you store the id corresponding to the correct coordinate. You can address a specific rectangle by using _objects[<X>/<Y>]. And if you need to know the coordinate you can simply iterate over the dic with:

def getCoordById(oid):  
    # Search with id
    for pairs in _objects.items():
        if pairs[1] == oid:
            return pairs[0]

canvas.itemconfig(_objects[getCoordById(1)], fill = "purple")

Ps.: If you always use the ID to identfy a coordinate I would use the canvas.create(...) as key and the name as value.

Upvotes: 1

Related Questions