0
votes

I want to close the window from plt.show() by pressing any key from my keyboard. At the moment,I don't know why, I need to press a key two times for the window to be closed.

Here's my code:

# -*- coding: utf-8 -*-
import datetime
import os
import psycopg2
import matplotlib.pyplot as plt


try:
    conn = psycopg2.connect("dbname='mydb' user='mysur' host='localhost' password='mypw'")
except psycopg2.DatabaseError, ex:
    print 'I am unable to connect the database: ' + str(ex)

cur = conn.cursor()




cur.execute("select day, avg_price from day_sumary where day > '2018-05-20' and coin_nome = 'LTC'")
records = cur.fetchall()

coin_nome_sql = 'LTC'

cur.execute("select day, amount from day_sumary where day > '2018-05-20' and coin_nome = '"+ coin_nome_sql+"'")
records = cur.fetchall()
print(coin_nome_sql)
day, amount = zip(*records)
# graph code
plt.plot(day, amount, label= coin_nome_sql)
# draw a grid
plt.grid()

conn.commit()
cur.close()
conn.close()
# set title, X/Y labels
plt.title("amount per day")
plt.xlabel("day")
plt.ylabel("amount")
plt.legend()
plt.show()
plt.waitforbuttonpress(0)
plt.close()
1
You might find it beneficial not to confuse reader with some database input they have no chance of reproducing anyways. See minimal reproducible example. - ImportanceOfBeingErnest

1 Answers

1
votes

You can use plt.draw() instead of plt.show(), as in

    plt.draw()
    plt.waitforbuttonpress(0)
    plt.close()

Beware: it will also close the window upon mouse click.

Non-elegant way around it:

    plt.draw()
    while True:
        if plt.waitforbuttonpress(0) == True:
            plt.close()
            break