在Python Tkinter窗口中显示Google地图API

6 投票
2 回答
18609 浏览
提问于 2025-04-16 14:29

你好,我正在用Python做Google地图的开发。我使用的源代码可以在这个网站找到。

这个代码编译后会生成一个'htm'文件,里面显示了一个Google地图,并且在地图上放置了标记。

所以我创建了一个窗口框架,如下所示:

from Tkinter import *  # order seems to matter: import Tkinter first
import Image, ImageTk  # then import ImageTk
class MyFrame(Frame):
    def __init__(self, master, im):
        Frame.__init__(self, master)
        self.caption = Label(self, text="Some text about the map")
        self.caption.grid()
        self.image = ImageTk.PhotoImage(im) # <--- results of PhotoImage() must be stored
        self.image_label = Label(self, image=self.image, bd=0) # <--- will not work if 'image = ImageTk.PhotoImage(im)'
    self.image_label.grid()
    self.grid()

im = Image.open("test.html") # read map from disk

# or you could use the PIL image you created directly via option 2 from the URL request ...
mainw = Tk()
mainw.frame = MyFrame(mainw, im)
mainw.mainloop()

我想在这个窗口框架里显示这个'htm'文件里的Google地图图像。

2 个回答

3

如果有人想在他们的Tkinter应用程序中放一个可以互动的谷歌地图小工具,就像上面的例子那样,我写了一个小库,可以显示基于瓦片的地图。默认使用的服务器是OpenStreetMap,但你也可以换成谷歌地图。不过要注意,谷歌地图的瓦片服务器已经不再更新,未来可能会有用不了的时候。

文档地址:https://github.com/TomSchimansky/TkinterMapView

安装方法:pip3 install tkintermapview

使用下面的代码,你就可以在Tkinter窗口中得到一个完全可用的谷歌地图小工具:

import tkinter
from tkintermapview import TkinterMapView

root_tk = tkinter.Tk()
root_tk.geometry(f"{600}x{400}")
root_tk.title("map_view_simple_example.py")

# create map widget
map_widget = TkinterMapView(root_tk, width=600, height=400, corner_radius=0)
map_widget.pack(fill="both", expand=True)

# google normal tile server
self.map_widget.set_tile_server("https://mt0.google.com/vt/lyrs=m&hl=en&x={x}&y={y}&z={z}&s=Ga", max_zoom=22)

map_widget.set_address("Berlin Germany", marker=True)

root_tk.mainloop()
5

htm图像pymaps生成的其实不是一张图片,而是一个html文件。简单来说,它就像一个小网页。要显示这个文件,你需要把html渲染出来。我知道的在TkInter中唯一的html渲染器是 TkHTML,不过我自己没用过,所以不确定它是否支持你html文件中用到的所有javascript。

其实,完全放弃TkInter,换成一个更现代的工具包,比如wxPython,会更好,因为wxPython自带html渲染功能。你可以在这里查看wxPython中html的文档 这里。如果你的系统上有GTK,我用过 pywebkitgtk,效果不错。

不过,你需要渲染这个框架是为了什么特定的目的吗?如果你只是想从python打开这个文件,可以使用内置的 webbrowser库,它可以用你的默认浏览器打开这个文件。

import webbrowser

webbrowser.open('test.htm')

就这样。

撰写回答