首页 > 解决方案 > 如果 gmaps.figure() 不是最后一行代码,gmaps 不显示地图?

问题描述

在这个程序中,我正在创建一个聊天机器人,它将以我将询问的某个位置的坐标进行响应,然后将这些坐标传递给

gmaps.figure()

该程序运行良好,如果

gmaps.figure(center=coordinates, zoom_level=zoom)

是代码的最后一行。但是,如果我在 if 正文下包含此行,则代码不会显示任何错误,但地图也不可见。

代码的注释部分是我看不到地图的地方。

这个简单的例子有效。


import gmaps
gmaps.configure(api_key=my_key)
print(type(30.2690717))
new_york_coordinates = (30.2690717, 77.9910673)
gmaps.figure(center=new_york_coordinates, zoom_level=17)

这可行,但是当代码的最后一行被删除并且 if is uncommented map 下的注释语句不显示时。

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
import os
import gmaps

bot = ChatBot("Bot")
trainer = ListTrainer(bot)
cor = []
for files in os.listdir("C://Users/Administrator/Desktop/Internship Project/chatterbot-corpus-master/chatterbot_corpus/data/english"):
    data = open("C://Users/Administrator/Desktop/Internship Project/chatterbot-corpus-master/chatterbot_corpus/data/english/"+files,'r').readlines()
    trainer.train(data)
gmaps.configure(api_key=my_key)


message = input('You:')
if(message.strip() != 'Bye'):
    reply = bot.get_response(message)
    cor = reply.text.split(',')
    lat = (float)(cor[0].strip('-'))
    lon = (float)(cor[1])
    zoom = (float)(cor[2])
    coordinates = (lat, lon)
    #gmaps.figure(center=coordinates, zoom_level=zoom)
gmaps.figure(center=coordinates, zoom_level=zoom)

即使gmaps.figure()不是代码的最后一行,我也希望看到地图图。

但是当gmaps.figure()不是代码的最后一行时没有错误但地图也没有显示。

标签: pythonpython-3.xjupyter-notebook

解决方案


gmaps.figure()返回 a Widget,这就是您面临此问题的原因。为了在任何给定时间(在您的情况下为任何行)呈现小部件,只需使用IPython'sdisplay函数。

import gmaps
from IPython.display import display

#...
# suppose you have multiple figures to show, here is one
fig1 = gmaps.figure(..)
# simply use display to render the figure
display(fig1)

# ... 
# and here's a second one after more lines of code
# and it no more needs to be the last line of code!
fig2 = gmaps.figure(..)
display(fig2)

# random code etc 

这使您可以随时渲染任何小部件。您不再需要在笔记本单元格的最后一行代码中显示您的图形来显示它。


推荐阅读