python - 通过键盘输入关闭 plt.show()
问题描述
我想通过按键盘上的任意键从 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()
解决方案
您可以使用plt.draw()
代替plt.show()
,如
plt.draw()
plt.waitforbuttonpress(0)
plt.close()
当心:它也会在鼠标点击时关闭窗口。
不优雅的方式:
plt.draw()
while True:
if plt.waitforbuttonpress(0) == True:
plt.close()
break
推荐阅读
- c++ - Xcode 中的 Googletest 没有看到测试代码发生了变化
- sql - sql 按列分组到同一行而不连接
- django - 弹性搜索模型init()引发关键错误
- java - 嵌套接口前面的static是什么意思?
- laravel - Laravel 5.7 多重身份验证
- java - 使用 AES 和 PBDKF2 加密的加密消息应包含哪些字段?
- swift - 全局函数调用协议类型的变异方法。如何摆脱 var tmp 对象?
- sql-server - SELECT Top (100) 比 Top (1) 快很多
- ruby-on-rails - 如果我缩短哈希中每个键名的长度,会缩短该哈希的读/写时间吗?
- c# - 使用 POCO 类、Unity 和 EF6 更新记录后的 Automapper 错误