繁体   English   中英

如何使用“onscreenclick”方法将坐标存储在 python 的字典中?

[英]How do i use the 'onscreenclick' method to store the coordinates in a dictionary in python?

我想创建一个关于猜测墨西哥州的游戏,所以我希望将 map 的坐标保存在字典中。 我的问题是 for 循环不能正常工作,因为这个程序只打印字典中的第一件事,而不是遍历整个字典。

# 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)

onscreenclick()无法按预期工作。

它仅将 function 分配给鼠标,稍后当您单击鼠标按钮时mainloop()将执行此 function。 它不会阻止代码,也不会在此时等待您的点击。

您只能运行一次,您必须在get_mouse_click_coor()中完成所有操作


最少的工作代码(但没有图像)

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)  

结果:

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]}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM