在将matplotlib嵌入到Tkinter中时,有没有办法更改NavigationToolbar的大小(例如zoom
按钮的大小)?我试图在width
中设置关键字height
和config
,但它不起作用。那么,有什么建议吗?
Update
import matplotlib
import os
import Tkinter as tk
from matplotlib.backends.backend_tkagg import NavigationToolbar2TkAgg as NavigationToolbar
from matplotlib.backends.backend_tkagg import ToolTip
class CustomedToolbar(NavigationToolbar):
def __init__(self, canvas, root):
NavigationToolbar.__init__(self,canvas,root)
def _Button(self, text, file, command, extension='.ppm'):
img_file = os.path.join(matplotlib.rcParams['datapath'], 'images', file + extension)
im = tk.PhotoImage(master=self, file=img_file)
im = im.zoom(3, 3)
im = im.subsample(4, 4)
# Do stuff with im here
b = tk.Button(master=self, text=text, padx=2, pady=2, image=im, command=command)
b._ntimage = im
b.pack(side=tk.LEFT)
return b
def _init_toolbar(self):
xmin, xmax = self.canvas.figure.bbox.intervalx
height, width = 50, xmax-xmin
tk.Frame.__init__(self, master=self.window,
width=int(width), height=int(height),
borderwidth=2)
self.update() # Make axes menu
for text, tooltip_text, image_file, callback in self.toolitems:
if text is None:
# spacer, unhandled in Tk
pass
else:
button = self._Button(text=text, file=image_file, command=getattr(self, callback))
if tooltip_text is not None:
ToolTip.createToolTip(button, tooltip_text)
self.message = tk.StringVar(master=self)
self._message_label = tk.Label(master=self, textvariable=self.message)
self._message_label.pack(side=tk.RIGHT)
self.pack(side=tk.BOTTOM, fill=tk.X)
这是我的努力。谢谢fhdrsdg。
答案 0 :(得分:1)
如果我理解你想要什么,你可以创建一个继承自NavigationToolbar2TkAgg
的自定义工具栏类。您可以更改创建按钮的_Button
定义:
class CustomToolbar(NavigationToolbar2TkAgg):
def _Button(self, text, file, command, extension='.ppm'):
img_file = os.path.join(matplotlib.rcParams['datapath'], 'images', file + extension)
im = Tk.PhotoImage(master=self, file=img_file)
# Do stuff with im here
b = Tk.Button(
master=self, text=text, padx=2, pady=2, image=im, command=command)
b._ntimage = im
b.pack(side=Tk.LEFT)
return b
正如您所看到的,这里我们有一个图像文件im,它是您想要缩小的图像。 Tk.PhotoImage
只有subsample()
来执行此操作,这样可以缩小整个因素。例如,您可以im = im.subsample(2, 2)
将图像缩小两倍(或im = im.zoom(2, 2)
使图像变大两倍)。
也许对PIL更熟练的人可以告诉你是否有办法使用PIL来制作你想要的任何大小的图像,但我无法让它工作。