I am trying to design a page in tkinter to get the current value of scale and update a plot immediately withtout pressing any button. The code follows the same logic as this simplified code:
import tkinter as tk
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
def update_plot(a):
x = np.linspace(-10, 10, 400)
y = a * x**2
ax.clear()
ax.plot(x, y)
canvas.draw()
root = tk.Tk()
root.title("Quadratic Function Plot")
# Create a Scale widget to control the parameter 'a'
scale_a = tk.Scale(root, from_=0.1, to=2, resolution=0.1, orient="horizontal", label="Parameter 'a'", command=update_plot)
scale_a.pack()
# Create a matplotlib figure and subplot
fig, ax = plt.subplots()
canvas = FigureCanvasTkAgg(fig, master=root)
canvas_widget = canvas.get_tk_widget()
canvas_widget.pack()
# Initial plot with default parameter value
update_plot(1)
root.mainloop()
But I cannot get the result I want:
- There is a matplotlib plot pops up beside to my tkinter window.
- No update happens to my plot upon moving the Scale handle.
2 Answers 2
You can use Scale widget's command option to call update_plot function to updating the plot immediately without pressing any button, when ever the scale value changes. You can embed the matplotlib plot inside the Tkinter window as follow.
import tkinter as tk
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
def update_plot(a):
x = np.linspace(-10, 10, 400)
y = a * x**2
ax.clear()
ax.plot(x, y)
canvas.draw()
root = tk.Tk()
root.title("Quadratic Function Plot")
# Create a Scale widget to control the parameter 'a'
scale_a = tk.Scale(root, from_=0.1, to=2, resolution=0.1, orient="horizontal", label="Parameter 'a'", command=update_plot)
scale_a.pack()
# Create a matplotlib figure and subplot
fig, ax = plt.subplots()
canvas = FigureCanvasTkAgg(fig, master=root)
canvas_widget = canvas.get_tk_widget()
canvas_widget.pack()
# Initial plot with default parameter value
update_plot(1)
root.mainloop()
Do the code adjustments as needed. This will embed the matlabplot inside the Tkinter window and plot will update with the scale handle.
Here is a good reference for this : [Embedding in Tk]: https://matplotlib.org/stable/gallery/user_interfaces/embedding_in_tk_sgskip.html
Comments
Note that the value of argument a of update_plot() is of type string, so exception will be raised on the following line:
y = a * x**2
You need to convert a to float number at the beginning of update_plot():
def update_plot(a):
a = float(a)
...