python turtle goto 不允许负 float

标签 python python-3.x turtle-graphics

我正在尝试使用“turtle ”来显示国际空间站(ISS)在世界地图上的位置。我从 API 中获取了经度和纬度。然后将坐标保存到变量“lon”和“lat”中。

但是当我使用 iss.goto(lon, lat) 时,我收到一个 TypeError。我相信这是由于经度和纬度坐标有时为负数造成的,因此 float 以“-”为前缀。

有人可以帮我解决这个问题吗?

import tkinter
import turtle
import json
import urllib.request

url = 'http://api.open-notify.org/iss-now.json'
response = urllib.request.urlopen(url)
result = json.loads(response.read())

location = result['iss_position']
lat = (location['latitude'])
lon = (location['longitude'])
print('latitude: ', lat)
print('longitude: ', lon)

screen = turtle.Screen()
screen.setup(3000, 1500)
screen.setworldcoordinates(-180, -90, 180, 90)
screen.register_shape('iss2.gif')

screen.bgpic('world_map.png')

iss = turtle.Turtle()
iss.shape('iss2.gif')
iss.setheading(90)
iss.penup()

iss.goto(lon, lat) #  I get the error here

tkinter.mainloop()

错误消息:

Traceback (most recent call last):
File "C:/Users/Ouch/PycharmProjects/Learning/Space_station.py", line 47, in     <module>
iss.goto(lon, lat)
File "C:\Python37\lib\turtle.py", line 1776, in goto
self._goto(Vec2D(x, y))
File "C:\Python37\lib\turtle.py", line 3165, in _goto
diff = (end-start)
File "C:\Python37\lib\turtle.py", line 262, in __sub__
return Vec2D(self[0]-other[0], self[1]-other[1])
TypeError: unsupported operand type(s) for -: 'str' and 'float'

最佳答案

错误是提示您无法从字符串中减去 float 。

因此,问题与某些 float 或某些 float 为负无关。您不能从字符串中减去 int,或从字符串中减去正 float ,或从字符串中减去任何其他内容。问题是您的某些值是字符串。

如果您打印出值的代表而不是直接打印值,您可以看到这一点:

print('latitude: ', repr(lat))
print('longitude: ', repr(lon))

你会看到类似这样的内容:

latitude:  '-10.4958'
longitude:  '-172.9960'

因此,要解决此问题,只需将这些字符串转换为 float 即可:

lat = float(location['latitude'])
lon = float(location['longitude'])

关于python turtle goto 不允许负 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52013948/

相关文章:

python - 更高效的时间增量计算 python 3

python - 只清除 turtle 图形中的一部分屏幕

Python: turtle 大小(以像素为单位)

Python 组合列表——保留相对顺序

python - 使用 python-matplotlib 连续 3D 绘图(即图形更新)?

python - python 中的 dfs 不工作请指导我有关错误

Python3.5/http/client.py 语法错误 : invalid syntax

python - 使用 Python Turtle 进行多线程处理

python - Matplotlib.pyplot.hist() 很慢

python - 多个按钮 Tkinter - Canvas 上的位置