问题
I'll try explain this as well as I can. I've created a function that uses Tkinter's tkFileDialog.askopenfilename() to let you select a photograph. The script comes back with the coordinates in two variables:
def getCoordinates():
# code to get coordinates here
# variables for lat and long
global latitude
global longitude
latitude
longitude
Now, I've created a function that calls the first function getCoordinates() TWICE. So this asks for TWO photographs to be selected.
def TwoPic():
run = 0
while run < 2:
run = run + 1
getCoordinates()
FirstRunLat = latitude
FirstRunLong = longitude
print FirstRunLat + " " + FirstRunLong
SecRunLat = latitude
SecRunLong = longitude
print SecRunLat + " " + SecRunLong
ThirdRunLat = latitude
ThirdRunLong = longitude
print ThirdRunLat + " " + ThirdRunLong
root.quit()
What basically will happen, is that the SecRunLat & SecRunLong and the ThirdRunLat & ThirdRunLong will end up being the same as FirstRunLat and FirstRunLong.
So what I'm asking is, how can I run the function to get coordinates and give the variables different names that stay unique and don't get duplicated if I run the function again?
Hope this makes sense.
Thank you very much in advance.
回答1:
Well, if you want to keep on using globals, I would just use lists:
def TwoPic():
run = 0
Lats = []
Longs = []
while run < 2:
run = run + 1
getCoordinates()
Lats.append(latitude)
Longs.append(longitude)
root.quit()
回答2:
You return values from your function, and assign them as a tuple:
def getCoordinates():
# code to get coordinates here
return latitude, longitude
and when calling these:
def TwoPic():
run = 0
while run < 2:
run = run + 1
FirstRunLat, FirstRunLong = getCoordinates()
print FirstRunLat + " " + FirstRunLong
SecRunLat, SecRunLong = getCoordinates()
print SecRunLat + " " + SecRunLong
ThirdRunLat, ThirdRunLong = getCoordinates()
print ThirdRunLat + " " + ThirdRunLong
root.quit()
Don't use globals to pass around function results; that's what the return
statement is for.
回答3:
What basically will happen, is that the
SecRunLat
&SecRunLong
and theThirdRunLat
&ThirdRunLong
will end up being the same asFirstRunLat
andFirstRunLong
.
Of course - you don't change the value in-between, as you call getCoordinates()
only once.
It would be much better to return your results:
def getCoordinates():
# code to get coordinates here
return latitude, longitude # as a tuple.
def TwoPic():
run = 0
results = []
while run < 2:
run = run + 1
lat, lng = getCoordinates()
print lat + " " + lng
results.append((lat, lng))
print results
root.quit()
来源:https://stackoverflow.com/questions/21403178/python-different-variable-with-each-function-run