I am having an issue with a project that aims to create a photo-editing tool in python. I have been using tkinter to code the GUI. The application encompasses muliple frames, which each represent a page of the GUI.
I haven't been able to find an article that covers this specific issue. Thanks in advance for any help!
The frame I am currently working on does the following:
For all images in a selected directory, a frame is created. These frames each contain a canvas, which contains the image itself, and two scrollbars. All frames are stacked on top of each other using the "grid" method and the user can switch back and forth between the frames with buttons.
This is what I am trying to do:
When the user presses a button, the coordinates of the image pixel he clicks on the canvas should be displayed to the terminal window.
This is what I have achieved until now:
When I click the canvas, coordinates are displayed on the terminal. These are the coordinates of the canvas pixel clicked, but not those of the image pixel. If I click the top left of the canvas, the coordinates x=0 and y=0 are printed to the window. This happens regardless of which part of the image is visible in the canvas.
This is what needs to be changed:
The program has to be aware that the canvas is only displaying a part of the image and has to analyze it globally. Usually this can be fixed with the .bbox('all') method, but I fear that my object-oriented approach is in my way.
This is a class that desribes one of the frames that contain a canvas with an image and scrollbars. This class is called by a function in a seperate class that "grids" multiple of these frames on top of each other.:
import tkinter as tk
from PIL import Image, ImageTk
class ImageFrame(tk.Frame):
def __init__(self, ParentFrame, path_to_image):
tk.Frame.__init__(self, ParentFrame)
self.path_to_image = path_to_image
self.width= self.winfo_screenwidth()
self.height= self.winfo_screenheight()
self.xscroll = tk.Scrollbar(self, orient='horizontal')
self.xscroll.grid(row=2, column=0, sticky='ew')
self.yscroll = tk.Scrollbar(self)
self.yscroll.grid(row=1, column=1, sticky='ns')
self.canvas = tk.Canvas(self, bd=0,
height=self.height - 150,
width=self.height - 150,
xscrollcommand=self.xscroll.set,
yscrollcommand=self.yscroll.set)
self.canvas.grid(row=1, column=0)
self.xscroll.config(command=self.canvas.xview)
self.yscroll.config(command=self.canvas.yview)
#adding the image
self.img = ImageTk.PhotoImage(Image.open(self.path_to_image))
self.canvas.create_image(0,0,image=self.img)
self.canvas.config(scrollregion=self.canvas.bbox('all'))
self.canvas.bind("<ButtonPress-1>",self.printcoords)
def printcoords(self, event):
#outputting x and y coords to console
x = self.canvas.canvasx(event.x)
y = self.canvas.canvasy(event.y)
print(x,y)
How do I get the pixel coordinates for a click on an image in a Canvas
, regardless of where on the canvas the image is?