Matplotlib with figure and slider

Good morning all,

I want to put a slider for scrolling on the X axis
The slider is in place, but I can’t access it with the mouse
does anyone have experience with this.
Thank you in advance for your assistance


# coding:utf-8
#version 3.x python
 
# ==================================================
#                                         ID python 3.7.2
# ==================================================
from tkinter import *
import tkinter as tk
from tkinter import ttk
print("TkVersion", TkVersion)
print("TclVersion", TclVersion)
print("Python version", sys.version_info)
import sys; print('Python %s on %s' % (sys.version, sys.platform))
 
# ==================================================
#                                         matplotlib 3.3.3
# ==================================================
from pylab import *                                                                                            # importe tout de matplotlib
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredAuxTransformBox
from matplotlib.widgets import Slider
 
print("MatPlotLib version : ", matplotlib.__version__)
print('MatPlotLib version : {}'.format(matplotlib.__version__))
 
# ==================================================
#                                  Notebook - Hauteur Largeur
# ==================================================
def _on_tab_changed(event):
	print("\n")
	'''
        update_idletasks
        Python est tkinter peuvent "mettre en sommeil" (idle) certaines tâches d'affichage, non essentielles, par exemple
        le redimensionnement des contrôles. Ces mises à jour de l'affichage sont dîtes dormantes. Pour forcer la mise à jour
        d'un tel affichage, utilisez .update_idletasks ( ) sans attendre la fin du traitement des gestionnaires d’événement et son retour au début de la boucle principale.
        '''
 
	nb = event.widget
	nb.update_idletasks()
 
	tab = nb.nametowidget(nb.select())
 
	nb.configure(height=tab.winfo_reqheight())														# Dimensionnement Hauteur
	nb.configure(width=tab.winfo_reqwidth())													    # Dimensionnement Largeur
 
 
def Create_notebook(master=None, **kw):
	nb = ttk.Notebook(master, **kw)
	nb.bind("<<NotebookTabChanged>>", _on_tab_changed)
	return nb
 
# ==================================================
#                                  Fenêtre Principal - Configuration
# ==================================================
root = tk.Tk()                                                                                                    # Crée une instance Tk class
root.title("Titre")
root.resizable(False, False)                                                                                 # Fenêtre verrouillée
 
window_height = 800
window_width = 900
 
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
 
x_cordinate = int((screen_width/2) - (window_width/2))
y_cordinate = int((screen_height/2) - (window_height/2))
 
root.geometry("{}x{}+{}+{}".format(window_width, window_height, x_cordinate, y_cordinate))
 
# ==================================================
#                                  Frames
# ==================================================
 
# --- Frame gauche ---
RightFrame = tk.LabelFrame(root, text="[Label]", font=('verdana', 8, ''), foreground="blue", relief=SOLID, borderwidth=0)
RightFrame.place(x=130, y=5, width=900, height=900)
RightFrame.anchor(anchor="center")
 
# Notebook
notebook = Create_notebook(RightFrame)
notebook.add(tk.Frame(notebook, bg="white", width=709, height=725, name="1"), text="GRAPH")
notebook.place(x=5, y=5)
 
'''  ===                                          ONGLET 1                                            === '''
 
 
Liste_TEST = [11.81, 4.91, 4.62, 4.19, 4.35, 4.22, 4.03, 4.31, 4.06, 4.23, 4.01, 4.28, 4.06, 3.81, 4.05, 4.04, 4.13, 4.08, 3.99, 4.05, 4.15, 4.26, 4.3, 4.35, 4.77, 4.65, 4.77, 4.52, 4.6, 11.81, 4.91, 4.62, 4.19, 4.35, 4.22, 4.03, 4.31, 4.06, 4.23, 4.01, 4.28, 4.06, 3.81, 4.05, 4.04, 4.13, 4.08, 3.99, 4.05, 4.15, 4.26, 4.3, 4.35, 4.77, 4.65, 4.77, 4.52, 4.6,11.81, 4.91, 4.62, 4.19, 4.35, 4.22, 4.03, 4.31, 4.06, 4.23, 4.01, 4.28, 4.06, 3.81, 4.05, 4.04, 4.13, 4.08, 3.99, 4.05, 4.15, 4.26, 4.3, 4.35, 4.77, 4.65, 4.77, 4.52, 4.6, 11.81, 4.91, 4.62, 4.19, 4.35, 4.22, 4.03, 4.31, 4.06, 4.23, 4.01, 4.28, 4.06, 3.81, 4.05, 4.04, 4.13, 4.08, 3.99, 4.05, 4.15, 4.26, 4.3, 4.35, 4.77, 4.65, 4.77, 4.52, 4.6]
y2 = [1.46,1.51,1.52,1.5,1.56,1.57,1.66,1.65,1.61,1.61,1.61,1.63,1.65,1.65,1.64,1.66,1.63,1.63,1.63,1.61,1.7,1.73,1.73,1.73,1.69,1.72,1.72,1.71,1.74, 1.46,1.51,1.52,1.5,1.56,1.57,1.66,1.65,1.61,1.61,1.61,1.63,1.65,1.65,1.64,1.66,1.63,1.63,1.63,1.61,1.7,1.73,1.73,1.73,1.69,1.72,1.72,1.71,1.74,1.46,1.51,1.52,1.5,1.56,1.57,1.66,1.65,1.61,1.61,1.61,1.63,1.65,1.65,1.64,1.66,1.63,1.63,1.63,1.61,1.7,1.73,1.73,1.73,1.69,1.72,1.72,1.71,1.74, 1.46,1.51,1.52,1.5,1.56,1.57,1.66,1.65,1.61,1.61,1.61,1.63,1.65,1.65,1.64,1.66,1.63,1.63,1.63,1.61,1.7,1.73,1.73,1.73,1.69,1.72,1.72,1.71,1.74]
 
chiffre_inf = IntVar()
chiffre_inf.set(floor(min(Liste_TEST)))                                                   # arrondi au plus bas
chiffre_sup = IntVar()
chiffre_sup.set(ceil(max(Liste_TEST)))                                                  # arrondi au plus haut
print("chiffre_inf", chiffre_inf.get(), "chiffre_sup", chiffre_sup.get())
 
 
# Crée un graphique de 1x1 (Y X) pouces avec une résolution de 96 points par pouce
fig = plt.Figure(figsize=(1, 1), dpi=96)
 
# Adjust the bottom size according to the
# requirement of the user
fig.subplots_adjust(bottom=0.25)
 
# Crée une vue dans une grille de 1 ligne x 1 colonne -- Y  X  GaucheDroite
ax1 = fig.add_subplot(1,1, 1, frameon=True, xlim=(0, len(Liste_TEST)), ylim=(chiffre_inf.get(), chiffre_sup.get()))
 
# Intégration du second axe Y [Right] - make twin axis based on axis X
ax2 = ax1.twinx()
 
# Affiche/Inhibe & Couleur -- Axes XY Haut-Bas - Droite-Gauche
# ['bottom'] ['top']
ax1.spines['bottom'].set_color('none')
ax1.spines['top'].set_color('none')
# ['right'] ['left']
ax2.spines['right'].set_color('#e45cda')   															# couleur rose
ax1.spines['left'].set_color('#FF0000')																	# couleur rouge
 
# Position Axe Y ['left']
ax1.yaxis.set_ticks_position('left')
ax1.spines['left'].set_position(('data', 0))
 
# Couleurs des Echelles de l'axe des abscisses et des deux xes des ordonnées
ax1.tick_params(labelcolor='#FF0000', left=True)
ax2.tick_params(labelcolor='#e45cda', right=True)
 
 
ax1.plot(range(len(Liste_TEST)), Liste_TEST, color="red", linewidth=.85, linestyle="dotted", label='Effective')
ax2.plot(range(len(Liste_TEST)), y2, color='#e45cda', linewidth=.85, linestyle="solid")
 
# Choose the Slider color
slider_color = 'White'
 
# Set the axis and slider position in the plot
# Origine XY = Coin BasGauche --> [Position Origine X, Position Origine Y, Longueur Barre. Largeur Barre]
axis_position = fig.add_axes([0.1, 0.96, 0.65, 0.03], facecolor=slider_color)
# Valeur de Départ - Fin de la Scrollbar
slider_position = Slider(axis_position, 'Pos', 0.1, 90.0)
 
# update() function to change the graph when the
# slider is in use
def update(val):
	pos = slider_position.val
	fig.axis([pos, pos+10, -1, 1])
	fig.canvas.draw_idle()
 
 
# update function called using on_changed() function
slider_position.on_changed(update)
 
graph = FigureCanvasTkAgg(fig, master=notebook.winfo_children()[0])
canvas = graph.get_tk_widget()
canvas.config(width=700, height=570, relief=RIDGE, borderwidth=2)
canvas.place(x=2, y=50)
 
 
root.mainloop()

You need to put this line: graph = FigureCanvasTkAgg(fig, master=notebook.winfo_children()[0]) before the creation of the slider. When you run that line it actually destroys the old canvas (which your slider had callbcaks hooked up to) and makes a new one.

2 Likes

thank you for your anwer.
now, it work