Ask Your Question
0

How can a button be utilized to display and hide the matplotlib live graph?

asked 2022-03-28 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-04-29 06:00:00 +0000

woof gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-03-28 11:00:00 +0000

Seen: 21 times

Last updated: Apr 29 '22