gpt4 book ai didi

python - 如何配置 MatPlotLib 工具栏,以便工具栏中的按钮是 ttk 按钮而不是旧的 Tk 按钮

转载 作者:行者123 更新时间:2023-12-01 06:37:26 25 4
gpt4 key购买 nike

我一直在考虑在我的 tkinter GUI 应用程序中嵌入 matplotlib 图形,但是在使用工具栏时,我不喜欢它的外观。谁能告诉我如何制作自己的按钮,将它们制作成ttk按钮,并将它们放在工具栏中?

最佳答案

您可以覆盖 NavigationToolbar2Tk 中的方法并为图标提供您自己的图像,如下所示:

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()

结果(自定义工具栏在顶部,原始工具栏在底部):

enter image description here

关于python - 如何配置 MatPlotLib 工具栏,以便工具栏中的按钮是 ttk 按钮而不是旧的 Tk 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59606641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com