0

The goal of this script is to ask for a file path after the button has been pressed, then the image should be opend and the user should be able to capture the coordinates of mouse clicks. For some reason, the image isn't been opened.

The block of code that open and place the image on the Tkinter canvas works fine by itself, but when I use it in such a way that the user is able to choose the file, it won't work.

class App:
    def __init__(self, master):
        myFrame = Frame(master)
        myFrame.pack()

        self.myButton = Button(master, text='Choose File', padx=40, pady=20, command=self.get_filepath)
        self.myButton.pack(pady=20)


    def get_filepath(self):
        self.path = file_path()

        def on_click(event):
            canvas = event.widget
            x = canvas.canvasx(event.x)
            coords.append(int(x))
            y = canvas.canvasy(event.y)
            coords.append(int(y))


        win = tk.Tk()

        win.geometry("1400x700")

        canvas = Canvas(win, width=1250, height=600, bg="white")
        canvas.grid(row=1, columns=1)

        # Add Images to Canvas widget
        image = cv2.imread(self.path)
        cv2image = cv2.cvtColor(image, cv2.COLOR_BGR2RGBA)
        img = Image.fromarray(cv2image)
        imgtk = ImageTk.PhotoImage(image=img)
        canvas.create_image(0, 0, anchor=NW, image=imgtk)

        canvas.config(scrollregion=canvas.bbox(ALL))

        canvas.bind("<Button-1>", on_click)

        # create a scrollbar widget and set its command to the text widget
        scrollbarY = ttk.Scrollbar(win, orient='vertical', command=canvas.yview)
        scrollbarY.grid(row=0, column=1, sticky=tk.NS)
        #  communicate back to the scrollbar
        canvas['yscrollcommand'] = scrollbarY.set

        scrollbarX = ttk.Scrollbar(win, orient='horizontal', command=canvas.xview)
        scrollbarX.grid(row=1, column=1, sticky=tk.NS)
        # communicate back to the scrollbar
        canvas['xscrollcommand'] = scrollbarX.set

        win.mainloop()

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
Hugo Pinho
  • 43
  • 5

0 Answers0