【问题标题】:Closing plt.show() by keyboard input通过键盘输入关闭 plt.show()
【发布时间】:2018-11-05 01:04:08
【问题描述】:

我想通过按键盘上的任意键从 plt.show() 关闭窗口。目前不知道为什么,需要按两次才能关闭窗口。

这是我的代码:

# -*- 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()

【问题讨论】:

  • 您可能会发现不要将阅读器与一些数据库输入混淆,因为它们无论如何都没有机会复制。见minimal reproducible example

标签: python matplotlib


【解决方案1】:

您可以使用plt.draw() 代替plt.show(),如

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

注意:鼠标点击时它也会关闭窗口。

不优雅的方式:

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

【讨论】:

    猜你喜欢
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 2016-08-25
    • 2015-10-19
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多