自动刷新的python ax窗口内容

2024-10-06 08:37:06 发布

您现在位置:Python中文网/ 问答频道 /正文

已知的错误是当线程是多线程的时候绘制窗口的plt.pause,而另一个线程需要窗口来绘制点,导致反应停滞

  • 有没有办法得到在我的窗口中绘制点的效果 动态显示,即逐步绘制点。或 允许自动刷新ax窗口内容的其他方法

我认为主要问题是由“plt.pause”命令引起的

  #-*-coding:utf-8-*-
    from matplotlib.patches import Circle
    import matplotlib.pyplot as plt
    import xlrd
    import numpy as np
    from matplotlib.animation import FuncAnimation
    import matplotlib.ticker as mticker
    import cartopy.crs as ccrs
    from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
    import time
    from matplotlib.offsetbox import AnnotationBbox,OffsetImage
    from PIL import Image
    import random
    from time import ctime,sleep
    import threading
     #地图可视化
    fig=plt.figure(figsize=(20,10))
    ax = plt.axes(projection=ccrs.PlateCarree())
    ax.coastlines()
    ax.stock_img()
    gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
                      linewidth=2, color='gray', alpha=15, linestyle='--')
    gl.xlabels_top = False
    gl.ylabels_left = False
    gl.xlines = False
    gl.xlocator = mticker.FixedLocator([-180, -45, 0, 45, 180])
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER
    gl.xlabel_style = {'size': 15, 'color': 'gray'}
    gl.xlabel_style = {'color': 'red', 'weight': 'bold'}
    img=Image.open(r'E:\python_file\untitled\p.png')
    imagebox=OffsetImage(img,zoom=0.05)
    imagebox.image.axes=ax
    ab=AnnotationBbox(imagebox,[55,10],pad=0,frameon=False)
    ax.add_artist(ab)
    ac=AnnotationBbox(imagebox,[63,0],pad=0,frameon=False)
    ax.add_artist(ac)
    ad=AnnotationBbox(imagebox,[70,-10],pad=0,frameon=False)
    ax.add_artist(ad)
    #============================================#攻击
    tolerance=1
    x_m1,y_m1=random.randint(-180,180),random.randint(-90,90)
    v_m1=170
    x_m2,y_m2=random.randint(-180,180),random.randint(-90,90)
    v_m2=v_m1
    x_m3,y_m3=random.randint(-180,180),random.randint(-90,90)
    v_m3=v_m1
    x_m4,y_m4=55,10
    x_m5,y_m5=63,0
    x_m6,y_m6=70,-10

    class target():
        """docstring for target"""
        def __init__(self, x, y):

            self.x = x
            self.y = y
    target1=target(x_m4,y_m4)
    target2=target(x_m5,y_m5)
    target3=target(x_m6,y_m6)
    v=v_m1

    class missile(threading.Thread):

        """docstring for missile"""

        def __init__(self, x, y,name):
            super(missile,self).__init__()
            self.x = x
            self.y = y
            self.name=name
        def forward(self, v, target1):
            """docstring for forward"""
            if self.x < target1.x:
                alpha = np.arctan((target1.y - self.y) / (target1.x - self.x))
            elif self.x > target1.x:
                alpha = np.pi + np.arctan((target1.y - self.y) / (target1.x - self.x))
            elif self.x == target1.x and self.y < target1.y:
                alpha = np.pi / 2
            else:
                alpha = -np.pi / 2
            self.x = self.x + v * 0.01 * np.cos(alpha)
            self.y = self.y + v * 0.01 * np.sin(alpha)
            return self.x, self.y
        def distance(self, target1):
            """docstring for distance"""
            return np.sqrt((self.x - target1.x) ** 2 + (self.y - target1.y) ** 2)

        def run(self):

            while True:

                if self.distance(target1)<self.distance(target2) and self.distance(target1)<self.distance(target3):
                    if self.distance(target1)<tolerance:
                            print ("collision")

                            break
                    else:
                          self.x,self.y=self.forward(v,target1)

                if self.distance(target2)<self.distance(target1) and self.distance(target2)<self.distance(target3):
                    if self.distance(target2)<tolerance:
                            print ("collision")
                            break
                    else:
                          self.x,self.y=self.forward(v,target2)

                if self.distance(target3)<self.distance(target2) and self.distance(target3)<self.distance(target1):

                    if self.distance(target3)<tolerance:
                            print ("collision")


                            break
                    else:
                          self.x,self.y=self.forward(v,target3)
                print "qian jin"

                plt.plot(self.x, self.y, 'bx')
                print "ok2"
                plt.pause(0.1)#the commond
    m2=missile(x_m2,y_m2,'mm')
    m1=missile(x_m1,y_m1,'mn')
    m3=missile(x_m3,y_m3,'md')
    m1.start()
    m2.start()
    m3.start()
    plt.show()

这些是所有代码


Tags: importselfalphanppltrandomaxm3
1条回答
网友
1楼 · 发布于 2024-10-06 08:37:06

你可以试试

fig.canvas.flush_events()

之所以使用plt.pause()是因为matplotlib打印时,它首先生成打印所需的结构,然后更新屏幕。但是如果它不断地得到新的数据来绘图,它就永远不会更新屏幕(以便忙于绘图)。因此,暂停几秒钟就可以给matplotlib更新屏幕的时间。图形的flush\u events函数强制matplotlib更新屏幕而不暂停

相关问题 更多 >