Reputation: 23
So I'm creating a image-to-word matching game on Tkinter in Python. The user can select how many images/words they'd like to play with/match, and I need a red rectangle to correspond to each image. The code that I used to create these rectangles is as follows:
for item in wordList: ##creating the image and its corresponding rectangle
cv.create_image(xVal*i, 100, image=item[0])
cv.create_rectangle(xVal*(i-1)+10, 445, xVal*(i+1)-10, 475, fill="red")
i += 2
Where wordList is the list of images that will be shown to the user. What I wanted to do is have the rectangle for each image turn green if the user enters the right word into an Entry widget. However, I have no idea how to access/config the rectangles that were made.
Any ideas?
Upvotes: 0
Views: 609
Reputation: 385980
Every time you create an item on a canvas, the function will return a unique id. You can use that id laster as the first argument to the itemconfigure
method. You just need to store those ids and use them later.
Alternatively, if each word in wordList
is unique, you can use the word as a tag, and treat the tag as if it were the unique id. In the following example, both the image and rectangle have the word as a tag. The rectangle also has a tag that is the word with the prefix "rect-".
for item in wordList: ##creating the image and its corresponding rectangle
cv.create_image(xVal*i, 100, image=item[0], tags=(item,))
cv.create_rectangle(xVal*(i-1)+10, 445, xVal*(i+1)-10, 475, fill="red",
tags=(item, "rect-"+item))
i += 2
With that, you could configure the rectangle for the word "hello" with something like this:
cv.itemconfigure("rect-hello", fill="green")
Upvotes: 1