在Tkinter中更改matplotlib的NavigationToolbar大小

时间:2015-01-08 08:06:11

标签: python matplotlib tkinter

在将matplotlib嵌入到Tkinter中时,有没有办法更改NavigationToolbar的大小(例如zoom按钮的大小)?我试图在width中设置关键字heightconfig,但它不起作用。那么,有什么建议吗?

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。

1 个答案:

答案 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来制作你想要的任何大小的图像,但我无法让它工作。