Windows, PyCharm, Python, tkinter, Canvas, program question There are three circles in the tkinter Canvas code with different colors. I want it to call the recolor method when I click on a circle. Unfortunately, I just can’t specify the If else conditions. I want to click with the same mouse button. The first round is ok, but the rest of the rounds are not! How should I write the code so that when I click on any circle with the same mouse button, the circle turns blue?
import tkinter as tk
class CanvasEvents(tk.Tk):
def __init__(self):
super().__init__()
self.geometry('510x510+700+100')
self.title("Event")
self.canvas = tk.Canvas(self, bg='grey', width=500, height=500)
self.canvas.pack(pady=5)
kor1 = self.canvas.create_oval(20, 20, 100, 100, width=2, fill="orange")
kor2 = self.canvas.create_oval(220, 20, 300, 100, width=2, fill="red")
kor3 = self.canvas.create_oval(420, 20, 500, 100, width=2, fill="green")
self.canvas.tag_bind(kor1, '<Button-1>', self.object_click_event)
self.canvas.tag_bind(kor2, '<Button-1>', self.object_click_event)
self.canvas.tag_bind(kor3, '<Button-1>', self.object_click_event)
def object_click_event(self, event):
# If else ?????????????????????
self.canvas.itemconfigure(event.num, fill="blue")
print('Clicked object at: ', self.canvas.coords(event.num), event.num)
if __name__ == "__main__":
ablak = CanvasEvents()
ablak.mainloop()
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
Enter your email to get $200 in credit for your first 60 days with DigitalOcean.
New accounts only. By submitting your email you agree to our Privacy Policy.
Hey @tvcsop,
You saw your comment about the code being legit, having said that, I think you need to adjust the
object_click_event
method to change the color of the clicked item. You can access the clicked item using thetag_closest
method and then change its color usingitemconfigure
.Something like this one here:
In the
create_oval
method, I added atags
parameter which can be used to bind the click event for each circle. Theobject_click_event
method usesfind_closest
to find the closest item to the clicked point. It then usesitemconfigure
to change the color of the clicked item to blue.The code is legible, I forgot to enter it! https://www.onlinegdb.com/ODwJiVxOY