Home > Software design >  clickable circle on canvas in tkinter
clickable circle on canvas in tkinter

Time:09-14

I was trying to create LUDO game in python for that I've created the coins using tkinter but now I'm unable to make it clickable button as it's int

self.r1 = self.create_canvas.create_oval(67, 58, 91, 83, width = 3, fill = "#ff0000")

now help me this coin act as btn

I want it to move when clicked.

CodePudding user response:

You can use canvas.tag_bind(tag, event, callback) to execute function (callback) when you click (event <Button-1>) on item with selected tag or ID (self.r1)

Other method is to bind <Button-1> to canvas and later use event.x,event.y with canvas.find_overlapping(x, y, x 1, y 1) to find all item which overlap region (x, y, x 1, y 1) and check if self.r1 in list_with_overlaping

You can use canvas.move(tag, offset_x, offset_y) or canvas.moveto(tag, x, y) to move object.


Minimal working code with both methods:

import tkinter as tk
import random

# --- functions ---

def on_canvas_click(event):
    print('on canvas click')

    print('event:', event)
    print('x, y :', event.x, event.y)
    overlaping = canvas.find_overlapping(event.x, event.y, event.x 1, event.y 1)
    print('overlaping:', overlaping)
    print('clicked:', circle_id in overlaping)
    
    if circle_id in overlaping:
        canvas.moveto(circle_id, random.randint(0, 500-24), random.randint(0, 500-25))
    
    print('-----')

def on_item_click(event):
    print('on item click')
    
    print('event:', event)
    print('x, y :', event.x, event.y)

    canvas.moveto(circle_id, random.randint(0, 500-24), random.randint(0, 500-25))

    print('-----')

# --- main ---

root = tk.Tk()

canvas = tk.Canvas(root, width=500, height=500)
canvas.pack()

canvas.bind('<Button-1>', on_canvas_click)

circle_id = canvas.create_oval(67, 58, 61 24, 58 25, width=3, fill="#ff0000")
canvas.tag_bind(circle_id, '<Button-1>', on_item_click)

root.mainloop()   

Doc from old effbot.org: The Tkinter Canvas Widget, Events and Bindings

  • Related