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