0

I have an embedded live matplotlib graph that updates every minute in a tkinter window. I want the graph to continue to update even when the window is closed. Also, when a person clicks a button, it will open the same tkinter window in it's updated state. Here is the code:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
import pytz 
root=Tk() 
root.title("Live Graph")
nextdate = datetime.datetime.today() + datetime.timedelta(days=1)
todaydate = date.today()

def plotcom():
     fig = plt.figure(figsize = (8,6))
     ax1 = fig.add_subplot(1, 1, 1)
     var5 = "TSLA"
     def animate(i):
           tickerData = yf.Ticker(var5)
           dsp = tickerData.history(interval='1m', start = todaydate, end=nextdate)
           dspclose = dsp["Close"]
           ax1.set_xlabel("Time")
           date_form = DateFormatter("%H-%M-%S", tz=pytz.timezone("America/New_York"))
           ax1.xaxis.set_major_formatter(date_form)
           ax1.set_ylabel("Price")
           ax1.set_title(var5+" - Live Graph")
           ax1.legend()
     canvas = FigureCanvasTkAgg(fig, master = root)   
     canvas.draw()
     canvas.get_tk_widget().pack() 
     canvas.get_tk_widget().place(x=10, y=240)
     ani = animation.FuncAnimation(fig, animate, interval = 60000)
     plt.show()
x = Button(root, text="Plot", command=plotcom)
x.pack()
x.place(x=300, y=0)
root.mainloop()
Ryan
  • 110
  • 9
  • 1
    You can hide/unhide a window with `.withdraw()` and `.deiconify()`. It will still update contents while hidden. – progmatico Nov 21 '20 at 15:43
  • How can I hide the window instead of closing it when the user attempts to close it? – Ryan Nov 21 '20 at 16:55
  • 1
    You can register a function that calls that method, or `iconify` method, when the user tries to close the wiindow, specifying the `WM_DELETE_WINDOW` protocol. See [here](https://stackoverflow.com/questions/111155/how-do-i-handle-the-window-close-event-in-tkinter) – progmatico Nov 22 '20 at 19:58
  • Oh okay. Thanks. Really helped – Ryan Nov 23 '20 at 06:46

0 Answers0