【问题标题】:python turtle goto not allowing a negative floatpython turtle goto 不允许负浮点数
【发布时间】:2018-08-25 04:05:00
【问题描述】:

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

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

谁能帮我解决这个问题?

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'

【问题讨论】:

  • 试试print(type(lat))

标签: python python-3.x turtle-graphics


【解决方案1】:

错误是抱怨你不能从字符串中减去浮点数。

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

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

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

你会看到这样的东西:

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

所以,要解决这个问题,只需将这些字符串转换为浮点数:

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

【讨论】:

    猜你喜欢
    • 2020-10-11
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多