Reputation: 909
I have a script that embeds a simple plot into a Tkinter gui. There is a button to plot, when it pressed it seems to do nothing, yet if the window is even slightly resized the plot pops up. The gui window is large enough to contain the plot, what am I doing wrong here?
Code
print('\n'*3)
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
#MAKE ROOT WINDOW
root = tk.Tk()
root.title("Tab Widget")
#root.geometry("600x450")
#MAKE A FIGURE OBJECT
my_figure = Figure(figsize = (4, 4), dpi = 100)
#MAKE A FRAME WIDGET
frame1 = tk.Frame(root, bd=2, relief=tk.GROOVE)
frame1.pack(side=tk.LEFT, anchor=tk.N, fill=tk.BOTH, expand=True)
frame2 = tk.Frame(root, bd=2, relief=tk.GROOVE)
frame2.pack(side=tk.RIGHT)
#MAKE A CANVAS OBJECT
my_canvas = FigureCanvasTkAgg(my_figure, master = frame1) # creating the Tkinter canvas containing the Matplotlib figure
# TURN THE CANVAS OBJECT INTO A CANVAS WIDGET
my_canvas.get_tk_widget().pack() # placing the canvas on the Tkinter window
my_canvas.draw()
def plotData():
plot1 = my_figure.add_subplot(111) # adding the subplot
x = [1,2,3,4,5]
y = [11, 3, 6, 9,12]
plot1.plot(x, y, marker='o', c='b')
# MAKE BUTTON TO PLOT GRAPH
button1 = tk.Button(frame2, text = "Plot", command = plotData, relief = tk.GROOVE, padx =20, pady =20 )
button1.pack(side="right")
root.mainloop()
Desired outcome
A gui window which does not need to be resized to see the plot.
Upvotes: 0
Views: 175
Reputation: 47163
You need to call my_canvas.draw()
at the end of plotData()
:
def plotData():
plot1 = my_figure.add_subplot(111) # adding the subplot
x = [1,2,3,4,5]
y = [11, 3, 6, 9,12]
plot1.plot(x, y, marker='o', c='b')
my_canvas.draw() # draw the graph
Upvotes: 1