-1

我是编码新手,想列出单击鼠标的位置的 x 和 y 坐标以在另一个文件中使用。

import turtle
import math

t = turtle.Turtle()
wn = turtle.Screen()


def rounds(x, y):
    t.setheading(t.towards(x, y)) #set x and y coord to mouse
    t.up()
    t.goto(x, y - 8) #move turtle to center of circle
    t.setheading(0) #makes turtle face set direction
    t.down()
    t.begin_fill()
    t.circle(8)
    t.end_fill()
    return x, y


def getcoord(): #draw function
    turtle.onscreenclick(rounds, 1) #run round every time left click 
    turtle.mainloop() # loops on screen click
4

1 回答 1

1

由于您是编码新手,如果您想从函数之外的函数中获取变量,一个重要的概念是scope,我建议您阅读它。您可以做的是在附加到的“全局”范围内引入一个变量:

import turtle
import math

t = turtle.Turtle()
wn = turtle.Screen()
click_positions = [] # will hold list of (x,y) click positions

def rounds(x, y):
    t.setheading(t.towards(x, y)) #set x and y coord to mouse
    t.up()
    t.goto(x, y - 8) #move turtle to center of circle
    t.setheading(0) #makes turtle face set direction
    t.down()
    t.begin_fill()
    t.circle(8)
    t.end_fill()
    click_positions.append((x,y)) # build a list of click positions in click_positions

    return x, y


def getcoord(): #draw function
    turtle.onscreenclick(rounds, 1) #run round every time left click 
    turtle.mainloop() # loops on screen click

您应该将点击位置存储在一个列表中,而不是两个单独的列表中。在另一个文件中,您可以访问数据:

from your_filename import click_positions
for click in click_positions:
   click_x, click_y = click # unpacks the python tuple (x,y) into two variables such that click_x=x, click_y=y
于 2020-04-18T00:24:54.113 回答