Matplotlib和Tkinter - 将轴导航模式设置回无

时间:2018-04-09 22:50:04

标签: python matplotlib tkinter

我试图在python 3中构建一个tkinter应用程序,它集成了matplotlib的FigureCanvasTkAgg后端。我使用NavigationToolbar2TkAgg创建一个导航栏小部件,它创建按钮以将轴导航模式更改为" PAN"和" ZOOM"。但是,默认情况下没有创建按钮会将导航模式更改回默认值(无)。我尝试创建一个自定义函数并将其绑定到一个按钮:self.select_button = tk.Button(self,command = lambda:self.ax.set_navigate_mode(None)).pack(side=tk.LEFT,anchor=tk.W)但是当单击该按钮时轴保持在平移模式。更大的代码段:

import tkinter as tk
import matplotlib.pyplot as plt 
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.backends.backend_tkagg import NavigationToolbar2TkAgg
from matplotlib.figure import Figure
matplotlib.use('TkAgg')

class Viewer(tk.Frame):
    def __init__(self, parent, collection=None, with_toolbar=True):
        tk.Frame.__init__(self, parent)
        self.fig = plt.Figure(figsize=(8, 6)) 
        self.ax = self.fig.add_subplot(111)
        self.canvas = FigureCanvasTkAgg(self.fig, master=self)
        self.navbar = NavigationToolbar2TkAgg(self.canvas, self)
        self.select_button = tk.Button(self,command = 
            lambda:self.ax.set_navigate_mode(None))
            .pack(side=tk.LEFT,anchor=tk.W)

以下是我尝试使用的文档:https://matplotlib.org/api/axes_api.html

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

NavigationToolbar2TkAgg类附带方法panzoom,分别用于切换平移和缩放模式。不是直接致电set_navigate_mode,而是使用get_navigate_mode检查当前导航模式,然后调用相应的切换方法。

self.navbar = NavigationToolbar2TkAgg(self.canvas, self)
...
if self.ax.get_navigate_mode == 'PAN':
    self.navbar.pan()
elif self.ax.get_navigate_mode == 'ZOOM':
    self.navbar.zoom()