簡體   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