import matplotlib.pyplot as plt
import pandas as pd
l1 = [1,2,3,4]
l2 = [2,4,6,8]
fig = plt.figure()
def func():
plt.pause(1)
plt.plot(l1,l2)
plt.draw()
plt.pause(1)
input("press any key to continue...")
plt.close(fig)
plt.pause(1)
while True:
func()
plt.pause(1)
这是修改后的:
import matplotlib.pyplot as plt
import pandas as pd
l1 = [1,2,3,4]
l2 = [2,4,6,8]
fig = plt.figure()
a = 1
def func(num):
input(f"the {num}th window is not opened yet")
plt.pause(1)
plt.plot(l1,l2)
plt.draw()
print(f"the {num}th window is opened")
plt.pause(1)
input("press any key to continue...")
plt.close(fig)
plt.pause(1)
print(f"the {num}th window is closed")
while True:
func(a)
plt.pause(1)
a+=1
如果我不使用 while True 循环,当我按任意键时它就会停止运行,这就是我的意图。但是,如果我使用 while True 循环运行此代码,即使我按左上角的任意键或 x 按钮,图形窗口也不会关闭。我认为这是由于 while True 。我不知道如何解决这个问题,保持 True 。请帮助我!
问题不在于
while True:
,而在于如何创建图形。让我们从概念上逐步了解您的流程:
fig = plt.figure()
创建一个图形并将句柄存储在 fig
中。func
,它会在图形上绘制并最终调用 plt.pause(1)
。func
。这次,plt.plot(l1, l2)
创建了一个new图形,因为没有开放的图形。func
致电plt.close(fig)
。但是存储在 fig
中的句柄不是您打开的 new 图形,所以您的图形当然不会关闭。要关闭正确的图形,请打开
func
内的图形。使用面向对象的 API 可以让您更好地控制打开、关闭、绘图等内容:
import matplotlib.pyplot as plt
import pandas as pd
l1 = [1, 2, 3, 4]
l2 = [2, 4, 6, 8]
def func():
fig, ax = plt.subplots()
ax.plot(l1, l2)
plt.show(block=False)
plt.pause(1)
input("press any key to continue...")
plt.close(fig)
plt.pause(1)
while True:
func()
或者,您可以将
plt.close(fig)
替换为 plt.close()
,这相当于 plt.close(plt.gcf())
,这样您就不必知道新图形的句柄。