Is there a way to change the size of NavigationToolbar (eg the size of zoom
button) when embedding matplotlib into Tkinter? I have tried to set the keywords width
and height
in config
, but it did not work. So, any suggestion?
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)
This is my effort. Thanks fhdrsdg.
If I understand what you want correctly, you can create a custom toolbar class, which inherits from NavigationToolbar2TkAgg
. You can the alter the _Button
definition in which the buttons are created:
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
As you can see, here we have an image file im, which is the image you want to make smaller. Tk.PhotoImage
only has subsample()
to do this, which lets you shrink the images by a whole factor. For example you could do im = im.subsample(2, 2)
to make the images twice as small (or im = im.zoom(2, 2)
to make them twice as big).
Maybe someone who is more proficient with PIL could tell you if there's a way to use PIL to make the images any size you want, but I couldn't get that to work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.