Reputation: 855
I am working on task, in which I am displaying an image to user. User will click anywhere on image, and co-ordinates will be printed.
A Tkinter library canvas
is used for display of image to user, user is allowed to click anywhere on the image.
What is the problem with printcoords()
function — why isn't it displaying anything?
Here is the code.
from Tkinter import *
import ImageTk
from PIL import Image, ImageDraw
from Tkinter import Tk, Menu, Canvas
if __name__ == '__main__':
#function on mouse click
def printcoords(event):
print "tahir"
#outputting x and y coords to console
data.append([event.x,event.y])
print data
#mouseclick event
root = Tk()
img = Image.open("eurecat1.png")
# Draw grid
step_count = 50
draw = ImageDraw.Draw(img)
y_start = 0
y_end = img.height
step_size = int(img.width / step_count)
for x in range(0, img.width, step_size):
line = ((x, y_start), (x, y_end))
draw.rectangle(line, fill="black")
x_start = 0
x_end = img.width
for y in range(0, img.height, step_size):
line = ((x_start, y), (x_end, y))
draw.rectangle(((x_start,y), (x_end, y)), fill="black")
# loadImage(canvas, img)
filename = ImageTk.PhotoImage(img)
canvas = Canvas(root,height=img.size[0],width=img.size[0])
canvas.image = filename # <--- keep reference of your image
canvas.create_image(0,0,anchor='nw',image=filename)
canvas.pack()
canvas.config(scrollregion=canvas.bbox(ALL))
frame = Frame(root, bd=2, relief=SUNKEN)
frame.grid_rowconfigure(0, weight=1)
frame.grid_columnconfigure(0, weight=1)
xscroll = Scrollbar(frame, orient=HORIZONTAL)
xscroll.grid(row=1, column=0, sticky=E+W)
yscroll = Scrollbar(frame)
yscroll.grid(row=0, column=1, sticky=N+S)
canvas = Canvas(frame, bd=0, xscrollcommand=xscroll.set, yscrollcommand=yscroll.set)
canvas.grid(row=0, column=0, sticky=N+S+E+W)
xscroll.config(command=canvas.xview)
yscroll.config(command=canvas.yview)
frame.pack(fill=BOTH,expand=1)
data=[]
#function on mouse click
def printcoords(event):
print "tahir"
#outputting x and y coords to console
data.append([event.x,event.y])
print data
#mouseclick event
canvas.bind("<Button 1>", printcoords)
root.mainloop()
Upvotes: 1
Views: 118
Reputation: 36662
As @abamert mentioned, you have two functions with the same name, and the code you posted has un-necessary complications that are not useful to solve the problem.
Here is a minimal example that you can use to fix your code:
import Tkinter as tk
def printcoords(event):
print event.x, event.y
if __name__ == '__main__':
root = tk.Tk()
canvas = tk.Canvas(root)
canvas.pack()
canvas.bind("<Button 1>", printcoords)
root.mainloop()
Upvotes: 1