Home > Back-end >  How do i use the 'onscreenclick' method to store the coordinates in a dictionary in python
How do i use the 'onscreenclick' method to store the coordinates in a dictionary in python

Time:08-22

I want to create a game about guessing the Mexico states, so i want the coordinates of the map be saved within a dictionary. My problem is that the for loop doesn't work properly because this program only prints the first thing in the dictionary and doesn't iterate through the entire dictionary.

# pylint: disable=E1101
import pandas
import turtle

#Adding the shape to the turtle then printing the map on the screen
screen = turtle.Screen()
screen.title('Estados de Mexico')
image = "map.gif"
screen.addshape(image)
turtle.shape(image)

#importing the names
states_data = pandas.read_csv('datos.csv')
names_dict={}

#global x and global y
gx = 0
gy = 0

def get_mouse_click_coor(x, y):
    global gx
    global gy
    gx = x
    gy = y
    print(x,y)

for name in states_data['estado']:
    print(name)
    turtle.onscreenclick(get_mouse_click_coor)
    names_dict[name] = [gx, gy]
    turtle.mainloop()
    turtle.onscreenclick(None)

CodePudding user response:

onscreenclick() doesn't work as you expect.

It only assigns function to mouse and later mainloop() will execute this function when you click mouse button. It doesn't block code and it doesn't wait for your click at this moment.

You can run it only once and you have to do all inside get_mouse_click_coor()


Minimal working code (but without image)

import pandas
import turtle

def get_mouse_click_coor(x, y):
    global name_index
    
    if name_index < len(names):
        # add coordinates with next `name` from
        name = names[name_index]
        names_dict[name] = [x, y]
        print(name, x, y)
        name_index  = 1
    else:
        # close window
        turtle.bye()
        print(names_dict)  # it will print after closing window
              
# --- main ---

names_dict = {}

#states_data = pandas.read_csv('datos.csv')
#names = states_data['estado'].to_list()
names = ['a', 'b', 'c']

name_index = 0

# assign function to mouse button
turtle.onscreenclick(get_mouse_click_coor)

# run loop which gets mouse/key events from system, sends them to widgets, and it will execute `get_mouse_click_coor` when you click mouse
turtle.mainloop()

# it will print after closing window
#print(names_dict)  

Result:

a -267.0 116.0
b 426.0 -136.0
c 437.0 139.0
{'a': [-267.0, 116.0], 'b': [426.0, -136.0], 'c': [437.0, 139.0]}
  • Related