Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to achieve this is to create a tkinter button and connect it to a function that will control the visibility of the matplotlib graph. Here's an example code snippet:

import tkinter as tk
import matplotlib.pyplot as plt

# create a matplotlib figure and axis
fig, ax = plt.subplots()
# plot some data on the axis
ax.plot([1, 2, 3], [4, 5, 6])

# create a function to be called when the button is clicked
def toggle_graph():
    if ax.get_visible():
        ax.set_visible(False)
    else:
        ax.set_visible(True)
    # redraw the figure to reflect the change in visibility
    fig.canvas.draw()

# create a tkinter window and button
root = tk.Tk()
button = tk.Button(root, text="Toggle Graph", command=toggle_graph)
button.pack()

# display the matplotlib graph in a tkinter canvas
canvas = plt.gcf().canvas
canvas.get_tk_widget().pack()

# start the tkinter event loop
root.mainloop()

In this example, the toggle_graph function uses the get_visible and set_visible methods of the matplotlib axis to toggle the visibility of the graph. The function also redraws the matplotlib figure using the canvas.draw method to reflect the change in visibility.

The matplotlib graph is displayed in a tkinter canvas widget using the get_tk_widget method of the matplotlib figure. The tkinter window and button are created using the standard tkinter functions. When the button is clicked, it calls the toggle_graph function to toggle the visibility of the matplotlib graph.