python如何重新运行程序怎么关闭_如何在python中关闭图并重新打开它?

So I have this code:

plt.style.use('bmh')

fig = plt.figure(figsize=(10,5))

ax = fig.add_subplot(111)

ax.plot(months, monthly_profit, 'b-',lw=3)

plt.xlabel('Monthhs')

plt.ylabel('Profit')

plt.yticks(np.arange(10000,25000,step=1500))

plt.title('Profit Chart')

play = True

while play:

x = int(input("State your choise : "))

if x == 3:

plt.show()

print("Would you like to continue? YES or NO?")

y = input()

if y == "NO":

play = False

plt.close("all")

And it seems like it doesn't close the plot at all. Not with close('all') ,nor with close(). What I'd like is to be able to open it and keep it open until the user states his answer, and afterwards ,close it.

Any help? :D

解决方案

The reason your plot does not close is because plt.show() blocks execution, so your code doesn't even reach the plt.close("all") line. To fix this you can use plt.show(block=False) to continue execution after calling show.

To reopen plots and have your loop work as I believe you are expecting it to, you need to move the plot creation logic to within the while loop. Note, however, that plt.style.use('bmh') must not be placed in this loop.

Here's an example:

import matplotlib.pyplot as plt

import numpy as np

# sample data

months = [1,2,3]

monthly_profit = [10, 20, 30]

plt.style.use('bmh')

play = True

while play:

fig = plt.figure(figsize=(10,5))

ax = fig.add_subplot(111)

ax.plot(months, monthly_profit, 'b-',lw=3)

plt.xlabel('Monthhs')

plt.ylabel('Profit')

plt.yticks(np.arange(10000,25000,step=1500))

plt.title('Profit Chart')

x = int(input("State your choise : "))

if x == 3:

plt.show(block=False)

print("Would you like to continue? YES or NO?")

y = input()

if y == "NO":

play = False

plt.close("all")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值