0

我正在尝试将 Matplotlib 底图添加到 TkInter 画布。但是,当我尝试绘制一个 Python 崩溃时,它不使用底图也可以正常工作。代码块 #1 是有效的代码,代码块 #2 使我的程序崩溃。如果我删除#2中的所有内容,除了m=Basemap(...)它也会崩溃的部分。计算Basemap(...)大约需要 6 或 7 秒,我猜这就是 TkInter 崩溃的原因。有什么想法可以告诉 TkInter 等待吗?

1:

def plot_route(self, geom1, root):
            root1 = Tk()

            x1, y1 = zip(*((geom1.GetX(i), geom1.GetY(i)) for i in range(geom1.GetPointCount())))
            f = Figure(figsize=(5,4), dpi=100)
            a = f.add_subplot(111)
            a.plot(x1,y1)
            a.set_title('Tk embedding')
            a.set_xlabel('X axis label')
            a.set_ylabel('Y label')

            canvas = FigureCanvasTkAgg(f, master=root1)
            canvas.show()
            canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
            canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)

            root1.mainloop()

2:

def plot_route(self, geom1, root):
            root1 = Tk()

            m = Basemap(width=12000000,height=9000000,projection='lcc', resolution='c',lat_1=45.,lat_2=55,lat_0=50,lon_0=-107.)
            m.drawcoastlines()
            m.drawmapboundary(fill_color='aqua')
            m.fillcontinents(color='coral',lake_color='aqua')

            canvas = FigureCanvasTkAgg(m, master=root1)
            canvas.show()
            canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
            canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)

            root1.mainloop()
4

1 回答 1

0

画布 = FigureCanvasTkAgg(m, master=root1)

我认为你不应该在这里使用'm'。

您应该创建一个图形,并添加一个子图 (ax),然后将该 ax 传递给底图。

并使用 fig 作为 FigureCanvasTkAgg 的参数。

import matplotlib
matplotlib.use('TkAgg')
from mpl_toolkits.basemap import Basemap
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

import sys
if sys.version_info[0] < 3:
    import Tkinter as Tk
else:
    import tkinter as Tk

root = Tk.Tk()
fig = Figure()  ## here
ax1 = fig.add_subplot(111)  ## here

m = Basemap(width=12000000,height=9000000,projection='lcc', 
            resolution='c',lat_1=45.,lat_2=55,lat_0=50,lon_0=-107.,
            ax=ax1) ## here
m.drawcoastlines()
m.drawmapboundary(fill_color='aqua')
m.fillcontinents(color='coral',lake_color='aqua')

canvas = FigureCanvasTkAgg(fig, master=root)  ## here
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

root.mainloop()
于 2013-10-29T16:40:44.247 回答