DenGor
DenGor

Reputation: 205

Understanding tkinter tag_bind

I cannot figure out how to use the tag_bind method associated with a canvas. I created an oval and expected to be able to generate an event by clicking on it. When I do this, nothing happens. What is the correct use of tag_bind?

import tkinter as tk

class Window():

    def __init__(self, master):
        self.master = master
        self.create_widgets()

    def create_widgets(self):
        self.c = tk.Canvas(self.master, bg='white', height=200, width=300)
        self.c.pack()

        b = tk.Button(self.master, text='Draw', command=self.draw)
        b.pack()

    def draw(self):
        self.c.delete('all')
        self.oval = self.c.create_oval([30,50], [130,80])
        self.rect = self.c.create_rectangle([180,10], [280,80])

        self.c.tag_bind(self.oval, '<Button-1>', self.oval_func)

    def oval_func(self, event):
        self.c.delete(self.rect)
        self.c.create_text(150, 150, text='Hello, world!', anchor='w')

if __name__ == '__main__':
    root = tk.Tk()
    app = Window(root)
    root.mainloop()

Upvotes: 1

Views: 11384

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385870

The code is working. However, when you bind to a canvas object, you have to click on part of the drawn object. Since you didn't fill the oval, that means you must click on its outline.

If you fill it with the same color as the background (or any other color) you can click anywhere in the oval.

self.oval = self.c.create_oval([30,50], [130,80], fill="white")

Upvotes: 3

Related Questions