1

I have a code that makes multiple canvases on Python tkinter (9 canvas). With this function (I destroy all item on window with destroy function at start):

def show_board(self):
    self.destroy_start()
    canvas_list = []
    for i in range(9):
        dist = {
            f"canvas{i + 1}": Canvas(height=150, width=150, bg=BOARD_COLOR),
        }
        canvas_list.append(dist)
    for n in range(len(canvas_list)):
        canvas_dict = canvas_list[n]
        for (key, val) in canvas_dict.items():
            if n == 0 or n <= 2:
                row = 0
                if n == 0:
                    col = 0
                    val.grid(row=row, column=col, padx=(125, 0))
                elif n == 1:
                    col = 1
                    val.grid(row=row, column=col)
                elif n == 2:
                    col = 2
                    val.grid(row=row, column=col)
            elif 2 < n <= 5:
                row = 1
                if n == 3:
                    col = 0
                    val.grid(row=row, column=col, padx=(125, 0))
                elif n == 4:
                    col = 1
                    val.grid(row=row, column=col)
                elif n == 5:
                    col = 2
                    val.grid(row=row, column=col)
            elif n > 5:
                row = 2
                if n == 6:
                    col = 0
                    val.grid(row=row, column=col, padx=(125, 0))
                elif n == 7:
                    col = 1
                    val.grid(row=row, column=col)
                elif n == 8:
                    col = 2
                    val.grid(row=row, column=col)
    # loop in canvas and get x and y of the click and set the image when user click
    for item in canvas_list:
        for (key, val) in item.items():
            canvas_x, canvas_y = val.winfo_rootx(), val.winfo_rooty()
            print(canvas_x, canvas_y)
            self.check_click(can=val)

    self.pl1_score_label.grid(column=0, row=3, padx=(100, 0))
    self.pl2_score_label.grid(column=2, row=3)

and I want to when user clicks on window on one of these canvases for the canvas to create an image (just than canvas) I try to do this with last loop in upper function

def display_mouse_pos(self, event):
    self.window.update()
    x = event.x
    y = event.y
    print(x, y)

def check_click(self, can):
    self.window.bind("<Button-1>", self.display_mouse_pos)
    can.create_image(100, 100, image=self.x_image)
    self.window.update()`

but I get that image on all canvas I know problem is my function and for loop I can't find the way to check if screen get clicked or not and if its get clicked which canvas get clicked and who can I make a picture in that canvas

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Pourya
  • 13
  • 3

0 Answers0