小工具知识网

当前位置: 首页 > 行业知识 > python Matplotlib Tkinter-->tab切换3

行业知识

python Matplotlib Tkinter-->tab切换3

2026-10-22 03:13:52 来源:互联网转载
环境

pythonindex.php/tags-41973.html" >:python-3.12.0-amd64

包:

matplotlib 3.8.2

pillow  10.1.0

import matplotlib.pyplot as pltfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tkimport tkinter as tkimport tkinter.messagebox as messageboximport tkinter.ttk as ttk# 创建自定义工具栏类class MyNavigationToolbar(NavigationToolbar2Tk):    toolitems = [('Home','回到初始状态','home','home'),                 ('Back', '后退', 'back', 'back'),                 ('Home', '前进', 'forward', 'forward'),                 ('Pan', '平移', 'move', 'pan'),                 ('Zoom', '缩放', 'zoom_to_rect', 'zoom'),                 ('Save', '保存', 'filesave', 'save_figure')]    def __init__(self, *args, **kwargs):        super().__init__(*args, **kwargs)    def __init__(self, canvas_, window_):        NavigationToolbar2Tk.__init__(self, canvas_, window_)        self.custom_button_img1 = tk.PhotoImage(file='figure_pic1.png')  # 创建第一个图片按钮        self.custom_button = ttk.Button(self, image=self.custom_button_img1, command=lambda: self.toggle_figure2())        self.custom_button.pack(side=tk.LEFT)  # 添加按钮到工具栏上        self.custom_button_img2 = tk.PhotoImage(file='figure_pic2.png')  # 创建第二个图片按钮        self.custom_button2 = ttk.Button(self, image=self.custom_button_img2, command=lambda: print('111.'))        self.custom_button2.pack(side=tk.LEFT)  # 添加按钮到工具栏上        self.fig2_visible = False  # 记录figure2的可见性    def toggle_figure2(self):        if self.fig2_visible:            canvas2.get_tk_widget().pack_forget()  # 隐藏figure2            self.fig2_visible = False        else:            canvas2.get_tk_widget().pack()  # 显示figure2            self.fig2_visible = True# 创建 Tkinter 窗口window = tk.Tk()window.title("Matplotlib in Tkinter")# 设置窗口大小和位置window.geometry('800x600')# 创建选项卡控件notebook = ttk.Notebook(window)# 创建第一个选项卡tab1 = ttk.Frame(notebook)fig1 = plt.figure()plt.plot([1, 2, 3], [4, 5, 6])canvas1 = FigureCanvasTkAgg(fig1, master=tab1)canvas1.draw()toolbar1 = MyNavigationToolbar(canvas1, tab1)toolbar1.update()toolbar1.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)canvas1.get_tk_widget().pack(fill=tk.BOTH, expand=True, padx=5, pady=5)notebook.add(tab1, text='图表1')# 创建第二个选项卡tab2 = ttk.Frame(notebook)fig2 = plt.figure()plt.plot([3, 2, 1], [6, 5, 4])canvas2 = FigureCanvasTkAgg(fig2, master=tab2)canvas2.draw()toolbar2 = MyNavigationToolbar(canvas2, tab2)toolbar2.update()toolbar2.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)canvas2.get_tk_widget().pack(fill=tk.BOTH, expand=True, padx=5, pady=5)notebook.add(tab2, text='图表2')notebook.pack(fill=tk.BOTH, expand=True)window.mainloop()

图片资源下载(分享-->python Matplotlib  Tkinter图片):

链接:https://pan.baidu.com/s/1vFOU52gG0bgK8RYuj-dzOg 

提取码:2oy0 

上一篇:Win10通知模式深度解析,轻松掌握通知设置指南

下一篇:Win10网速飞跃,解决网络限速,网速轻松提升!