Kivy更新matplotlib图

ggazkfy8  于 2023-03-09  发布在  其他
关注(0)|答案(1)|浏览(159)

开始学习Kivy,我想创建一个简单的应用程序,由一个开始页面(非常简单)和第二个页面组成,在第二个页面中我用一个按钮来绘制数据,以删除旧的绘图并显示新的绘图。
经过一些问题来控制绘图小部件的大小和位置,我可以显示2个页面和按钮,问题是当我点击"更新按钮"时,显示了一个新的绘图,但是在旧图的旁边又加了一张图,我多次返回第二页时,同样的问题又出现了,你知道如何重用旧图并更新/重置它还是如何修复它?
下面是我的代码:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen

from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg
import matplotlib.pyplot as plt
import numpy as np

                                            
## Here for providing colour to the background  
from kivy.core.window import Window 

## Setting the window size 
Window.clearcolor = (1, 1, 1, 1) # White background
Window.size = (960, 540) 

kv = """
#:import SlideTransition kivy.uix.screenmanager.SlideTransition

<Manager>:
    transition: SlideTransition()

    StartPage:
        name: 'StartPage'

    SecondPage:
        name: 'SecondPage'

<StartPage>:

    canvas:
        
        Color:
            rgba: 0.1, 0.1, 1, 0.7
            
        Rectangle:
            pos: 0, 11*root.height/12
            size: root.width, root.height/12
            
        Rectangle:
            pos: 0, 0
            size: root.width, root.height/12

        
    BoxLayout:
        orientation: 'vertical'
        size: root.width, root.height

    Button:
        size_hint: 0.15, 0.08
        pos_hint: {'left': 0, 'top': 1 }
        text: 'Go to Second Page'
        on_release:
            root.manager.current = 'SecondPage'
        
    Button:
        size_hint: 0.15, 0.08
        pos_hint: {'right': 1, 'bottom': 1 }
        text: 'Quit'
        on_release: app.stop()
    
                
    Label:
        text: 'Start Screen'
        font_size: '20sp'
        color: 0,0,0,1
        pos_hint:{'x': 0.42, 'y': 0.46 }

    

<SecondPage>:
    box: box

    canvas.before:
        Color:
            rgba: 1, 1, 1, 1
        Rectangle:
            pos: self.pos
            size: self.size

    BoxLayout:
        id: box
        size_hint: 0.8, 0.75
        pos_hint:{'x': 0, 'y': 0.1 }

    Button:
        text:'Start Menu'
        font_size: 20
        bold: True
        size_hint: 0.15, 0.08
        pos_hint: {'left': 0, 'top': 1 }
        color: 1, 1, 1, 1
        on_press: root.manager.current = 'StartPage'
        
    Button:
        text:'Update'
        font_size: 20
        bold: True
        size_hint: 0.15, 0.08
        pos_hint: {'x':0.8, 'y': 0.5 }
        color: 1, 1, 1, 1
        on_press: root.Update()
"""

Builder.load_string(kv)

# Start Page
class StartPage(Screen):      
    pass

#Second Page
class SecondPage(Screen):
    box = ObjectProperty(None)

    def add_plot(self, N):
    
        phase = np.random.normal(-np.pi/2, +np.pi/2)
        noise = np.random.normal(0, 1, N)
        nbr = np.linspace(0,1,N)
        func = 0.01*noise+np.sin(nbr/0.1+phase)
    
        plt.plot(nbr,func,label='Line1',color='r')
        plt.ylabel('Sinus')
        plt.xlabel('Range')
        plt.grid(True)
        self.fig1 = plt.gcf()
    
        return self.fig1

    def on_pre_enter(self, *args):
    
        self.fig1 = SecondPage.add_plot(self,1000)
        self.box.add_widget(FigureCanvasKivyAgg(self.fig1))
    
    def Update(self):
    
        self.box.remove_widget(FigureCanvasKivyAgg(self.fig1))
    
        self.fig1 = SecondPage.add_plot(self,1000)
        self.box.add_widget(FigureCanvasKivyAgg(self.fig1))

class Manager(ScreenManager):
    pass

class MyNewApp(App):
    title = "Matplolib - plot Update"

    def build(self):
        return Manager()    

MyNewApp().run()
oknwwptz

oknwwptz1#

一个确实有效的方法是一个相对容易的修复:如果您使用self.box.clear_widgets()清除所有子小部件,而不是指定小部件,则调用plt.cla()从图中删除之前的数据,应该执行您要执行的操作。
编辑代码如下:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen

from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg
import matplotlib.pyplot as plt
import numpy as np

## Here for providing colour to the background  
from kivy.core.window import Window 

## Setting the window size 
Window.clearcolor = (1, 1, 1, 1) # White background
Window.size = (960, 540) 

kv = """
#:import SlideTransition kivy.uix.screenmanager.SlideTransition

<Manager>:
    transition: SlideTransition()

    StartPage:
        name: 'StartPage'

    SecondPage:
        name: 'SecondPage'

<StartPage>:

    canvas:

        Color:
            rgba: 0.1, 0.1, 1, 0.7

        Rectangle:
            pos: 0, 11*root.height/12
            size: root.width, root.height/12

        Rectangle:
            pos: 0, 0
            size: root.width, root.height/12

    BoxLayout:
        orientation: 'vertical'
        size: root.width, root.height

    Button:
        size_hint: 0.15, 0.08
        pos_hint: {'left': 0, 'top': 1 }
        text: 'Go to Second Page'
        on_release:
            root.manager.current = 'SecondPage'

    Button:
        size_hint: 0.15, 0.08
        pos_hint: {'right': 1, 'bottom': 1 }
        text: 'Quit'
        on_release: app.stop()

    Label:
        text: 'Start Screen'
        font_size: '20sp'
        color: 0,0,0,1
        pos_hint:{'x': 0.42, 'y': 0.46 }


<SecondPage>:
    box: box

    canvas.before:
        Color:
            rgba: 1, 1, 1, 1
        Rectangle:
            pos: self.pos
            size: self.size

    BoxLayout:
        id: box
        size_hint: 0.8, 0.75
        pos_hint:{'x': 0, 'y': 0.1 }

    Button:
        text:'Start Menu'
        font_size: 20
        bold: True
        size_hint: 0.15, 0.08
        pos_hint: {'left': 0, 'top': 1 }
        color: 1, 1, 1, 1
        on_press: root.manager.current = 'StartPage'

    Button:
        text:'Update'
        font_size: 20
        bold: True
        size_hint: 0.15, 0.08
        pos_hint: {'x':0.8, 'y': 0.5 }
        color: 1, 1, 1, 1
        on_press: root.Update()
"""

Builder.load_string(kv)

# Start Page
class StartPage(Screen):      
    pass

#Second Page
class SecondPage(Screen):
    box = ObjectProperty(None)

    def add_plot(self, N):

        phase = np.random.normal(-np.pi/2, +np.pi/2)
        noise = np.random.normal(0, 1, N)
        nbr = np.linspace(0,1,N)
        func = 0.01*noise+np.sin(nbr/0.1+phase)

        plt.plot(nbr,func,label='Line1',color='r')
        plt.ylabel('Sinus')
        plt.xlabel('Range')
        plt.grid(True)
        self.fig1 = plt.gcf()

        return self.fig1

    def on_pre_enter(self, *args):

        self.fig1 = SecondPage.add_plot(self,1000)
        self.box.add_widget(FigureCanvasKivyAgg(self.fig1))

    def Update(self):
        #self.box.remove_widget(FigureCanvasKivyAgg(self.fig1))
        plt.cla()
        self.box.clear_widgets()
        self.fig1 = SecondPage.add_plot(self,1000)
        self.box.add_widget(FigureCanvasKivyAgg(self.fig1))

class Manager(ScreenManager):
    pass

class MyNewApp(App):
    title = "Matplolib - plot Update"

    def build(self):
        return Manager()    

MyNewApp().run()

相关问题