Home > Mobile >  tkinter - multiple variables at once
tkinter - multiple variables at once

Time:02-24

I have a tkinter program.

I want to get the effect where, after clicking on three places in the image, the program prints appropriate coordinates: initial (x1, y1), height (y2-y1) and width (x3-x1), so the first click - x and y, the second - height and the third - width.

At the moment I have a defined function "printcoords". When I click on the image, the function "bind" runs, which call "printcoords" function and the x and y coordinates are printed

#function to be called when mouse is clicked
def printcoords(event):
    #outputting x and y coords to console
    print (event.x, event.y)

#mouseclick event
canvas.bind("<Button 1>",printcoords)

CodePudding user response:

The following code roughly does what you are looking for.

import tkinter as tk

coords = []

def printcoords(event):
    global coords
    #print(event.x,event.y)
    coords.append((event.x,event.y))
    if len(coords) >= 3:
        print(coords)
        print(f"Initial: {coords[0][0]},{coords[0][1]}")
        print(f"Height: {coords[1][1]-coords[0][1]}")
        print(f"Width: {coords[2][0]-coords[0][0]}")
        coords = []
    

root = tk.Tk()
c = tk.Canvas(root,width=200,height=200,bg="lightyellow")
c.bind("<Button-1>",printcoords)
c.grid()
root.mainloop()

It stores the x/y coordinates in a list until the list contains 3 values, it will then print out the first set of coordinates followed by the height and width as per the algorithm in your question.

Using a global here isn't best practice but it works for such a simple example. In a more complex program, I'd store the coordinates in a class.

CodePudding user response:

from itertools import cycle

steps = cycle([1,2,3])
class Point:
    def __init__(self):
        self.x = 0
        self.y = 0

points = [Point() for _ in range(3)]

#function to be called when mouse is clicked
def printcoords(event):
    step = next(steps)
    p = points[step-1]
    p.x = event.x
    p.y = event.y
    if step==3:
        #outputting x and y coords to console
        print(f"Initial: {points[0].x},{points[0].y}")
        print(f"Height: {points[1].y-points[0].y}")
        print(f"Width: {points[2].x-points[0].x}")
    
#mouseclick event
canvas.bind("<Button 1>",printcoords)
  • Related