как сохранить переменные функции вне функции для использования в другом файле?
Я новичок в кодировании и хочу составить список координат 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
1 ответ
Решение
Поскольку вы новичок в кодировании, важной концепцией, если вам нужны переменные из функции вне функции, является концепция области, я предлагаю вам прочитать об этом. Что вы можете сделать, так это ввести переменную в "глобальную" область видимости, к которой вы добавляете:
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