python - 如果 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()
不是代码的最后一行时没有错误但地图也没有显示。
解决方案
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
这使您可以随时渲染任何小部件。您不再需要在笔记本单元格的最后一行代码中显示您的图形来显示它。
推荐阅读
- c# - GameManagerCompunet.MoveToNextStage()'由于其保护级别而无法访问
- android - 如何使用android的ptrace拦截系统调用(svc)?
- javascript - 显示 [object Object] 而不是标签名称
- vodapay-miniprogram - 有没有办法在整个小应用程序中禁用主页链接?
- sql - 从另一个字符串返回与正则表达式匹配的所有字符串的列表
- angular - 自定义管道Angular中的异步
- latex - Biblatex:网站引用为斜体,删除“nd”时使用标题而不是作者
- tcp - TcpClient sometimes seems not to finish a writing before closing/disposing. Why?
- graph - Merge overlapping paths
- reactjs - Next.js 刷新值而不在道具列表中重新加载页面