Python 如何配置MatPlotLib工具栏,使工具栏中的按钮是ttk按钮而不是旧的Tk按钮
我一直在考虑在tkinter GUI应用程序中嵌入matplotlib图,但在使用工具栏时,我不喜欢它的外观。有人能告诉我如何制作自己的按钮,制作ttk按钮,并将它们放入工具栏吗?您可以覆盖Python 如何配置MatPlotLib工具栏,使工具栏中的按钮是ttk按钮而不是旧的Tk按钮,python,windows,matplotlib,tkinter,Python,Windows,Matplotlib,Tkinter,我一直在考虑在tkinter GUI应用程序中嵌入matplotlib图,但在使用工具栏时,我不喜欢它的外观。有人能告诉我如何制作自己的按钮,制作ttk按钮,并将它们放入工具栏吗?您可以覆盖导航工具栏2TK中的方法,并为图标提供自己的图像,如下所示: from tkinter import * from matplotlib.backends.backend_tkagg import NavigationToolbar2Tk, FigureCanvasTkAgg from matplotlib.
导航工具栏2TK
中的方法,并为图标提供自己的图像,如下所示:
from tkinter import *
from matplotlib.backends.backend_tkagg import NavigationToolbar2Tk, FigureCanvasTkAgg
from matplotlib.figure import Figure
from matplotlib.backends._backend_tk import ToolTip
root = Tk()
class Navigator(NavigationToolbar2Tk):
"""
Customized Navigator object
- Removed mouse_move event.x and event.y display
- Changed buttons layout
"""
def mouse_move(self,event):
pass
def _Button(self, text, file, command, extension='.gif'):
im = PhotoImage(master=self, file=file)
b = Button(master=self, text=text, padx=2,image=im, command=command,bg="DeepSkyBlue4",relief="flat")
b._ntimage = im
b.pack(side=LEFT)
self.tool_buttons.append(b)
return b
def _init_toolbar(self):
self.tool_buttons = []
self.toolbar_icons = ["icons/home.png", #provide paths of your own icons
"icons/backward.png",
"icons/forward.png",
None,
"icons/pan.png",
"icons/zoom.png",
"icons/config.png",
None,
"icons/save.png"]
xmin, xmax = self.canvas.figure.bbox.intervalx
height, width = 50, xmax-xmin
Frame.__init__(self, master=self.window,
width=500, height=int(height))
self.update()
num = 0
for text, tooltip_text, image_file, callback in self.toolitems:
if text is None:
self._Spacer()
else:
try:
button = self._Button(text=text, file=self.toolbar_icons[num],
command=getattr(self, callback))
if tooltip_text is not None:
ToolTip.createToolTip(button, tooltip_text)
except IndexError:
pass
num+=1
self.pack(side=BOTTOM, fill=X)
def destroy(self, *args):
Frame.destroy(self)
f = Figure()
canvas = FigureCanvasTkAgg(f, root)
canvas.get_tk_widget().pack(fill=BOTH, expand=True)
toolbar = NavigationToolbar2Tk(canvas, root)
custom_toolbar = Navigator(canvas, root)
custom_toolbar.config(background="DeepSkyBlue4")
root.mainloop()
结果(顶部为自定义工具栏,底部为原始工具栏):
我曾经创建了
导航工具栏2TK
的子类,然后逐个修改相关的方法/参数。但是很痛,你会怎么做?我对如何更改按钮的参数感到困惑,因为工具栏是在matplotlib模块中硬编码的,这正是您需要将其子类化的原因——覆盖您需要修改的部分。我给你一个小样品。