0

I've got a program that on launch will open a matplotlib graph of bitcoin prices and will update every time the price changes. Then when I close it a fullscreen tkinter application opens with a background image and a updating clock in the corner. What I would like to happen is when I launch the program a fullscreen tkinter application opens with a background image, an updating clock in the corner, and the matplotlib graph in the middle. Basically I want to embed the matplotlib graph into my application. I've tried putting the graph code into my class and calling it but that just gives the results mentioned earlier. I tried replacing the plt.show() with this:

canvas = FigureCanvasTkAgg(fig, self) canvas.show() canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)

but then the program wasn't launching at all. No matter where I put it in the script it would give errors like ''self' is not defined' when I directly replaced plt.show()with it and ''canvas' is not defined' when I tried to integrate it into the class. Here is the full code below:

from tkinter import *
from PIL import ImageTk, Image
import os
import time
import requests
import tkinter as tk
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.animation as animation
from matplotlib import style
from tkinter import ttk
import urllib
import json
import pandas as pd
import numpy as np
from PyQt5 import QtWidgets

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

class App(tk.Tk):
    def __init__(self):
        # call the __init__ method of Tk class to create the main window
        tk.Tk.__init__(self)

        # background image
        img = ImageTk.PhotoImage(Image.open("0.png"))
        panel = Label(self, image=img)
        panel.pack()

        # clock
        self.label = tk.Label(self, text="", font=('comic',50,'bold'),
                          bg='#464545', fg='#1681BE')
        self.label.place(height=204, width=484, x=1384, y=824)       
        self.update_clock()

        # window geometry
        w, h = self.winfo_screenwidth(), self.winfo_screenheight()
        self.geometry("%dx%d+0+0" % (w, h))

        self.overrideredirect(True)
        self.mainloop()

    def update_clock(self):
        now = time.strftime('%H:%M:%S')
        self.label.configure(text=now)
        self.after(1000, self.update_clock)

    def animate(self): 

        dataLink = 'https://btc-e.com/api/3/trades/btc_usd?limit=2000d'
        data = urllib.request.urlopen(dataLink)
        data = data.read().decode("utf-8")
        data = json.loads(data)

        data = data["btc_usd"]
        data = pd.DataFrame(data)

        buys = data[(data['type']=="ask")]
        buys["datestamp"] = np.array(buys["timestamp"]).astype("datetime64[s]")
        buyDates = (buys["datestamp"]).tolist()

        plot(buyDates, buys["price"])

        xlabel('time')
        ylabel('Temperature')
        title('Temperature Chart')
        grid(True)


    ani = animation.FuncAnimation(fig, animate, interval=1000)

plt.show()
app = App()

There are a few dependable's like '0.png' which is the background image and of course the many modules but any feedback would be much appreciated.

2
  • I'm sorry I didn't mention this but I'm using python 3.5.2 Commented Mar 2, 2017 at 7:19
  • "but that didn't work either." is not a sufficient problem description. The code you show does not have "something to do with canvas" in it, appart from the import of FigureCanvasTkAgg which is never used. This makes it impossible to help you with the actual problem. Consider (re)reading How to Ask. You may edit your question, instead of writing comments below it. Commented Mar 2, 2017 at 7:54

1 Answer 1

0

plt.show() will open a new dedicated GUI window to host the figure(s) currently present in the matplotlib state machine. If you don't want that, don't use plt.show().
To be on the save side, best don't use pyplot at all as even such innocent commands as plt.xticks() can cause a new window to open.

Also, get rid of from pylab import *. Pylab is a construct which includes several packages like numpy and pyplot in a single namespace. This may be desired for interactive notebook-like applications, but is usually a bad idea for scripts, as it makes debugging very cumbersome. Instead, try to fully stick to matplotlib API commands.

This linked question actually is an example of how to use FigureCanvasTkAgg and NavigationToolbar2Tk to embed a figure into tk.

A better start might be to look at the matplotlib example page where a minimal example for tk embedding is presented.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.