插入带有 kv lang 的图形

我正在尝试制作一个带有 2 个屏幕的 APP:

  • 第一个屏幕是一个按钮

  • 第二个屏幕显示图表

当按下第一个屏幕的按钮时,第二个屏幕显示图形。我只能使用 matplotlib 用 1 个屏幕绘制图形。

这是我的代码:

from kivy.app import App

from kivy.uix.boxlayout import BoxLayout

from kivy.uix.screenmanager import ScreenManager, Screen

from kivy.lang import Builder

import matplotlib.pyplot as plt

import matplotlib

matplotlib.use("module://kivy.garden.matplotlib.backend_kivy")

from kivy.garden.matplotlib import FigureCanvasKivyAgg


from kivy.uix.widget import Widget



class Sensores(Screen):

    pass


class Grafico(Screen):

    def build(self):

        box = BoxLayout()

        box.add_widget(FigureCanvasKivyAgg(plt.gcf()))

        return box


class Menu(ScreenManager):

    pass


presentation = Builder.load_file('sensor.kv')


class sensor(App):

    def build(self):

        return presentation


if __name__ == "__main__":

    sensor().run()

基维


Menu:

    Sensores:

    Grafico:


<Sensores>

    name: 'sensores'

    BoxLayout:

        Button:

            text: "Sensor 01"

            on_release:

                root.Grafico()


<Grafico>

    name: 'grafico'

我希望在第二个屏幕中有图表。


狐的传说
浏览 220回答 2
2回答

qq_花开花谢_0

我发现您的代码有两个问题。首先,在您的kv文件中,Button操作不正确:&nbsp; &nbsp; Button:&nbsp; &nbsp; &nbsp; &nbsp; text: "Sensor 01"&nbsp; &nbsp; &nbsp; &nbsp; on_release:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; root.Grafico()如果Button打算切换到另一个屏幕,则应该是:&nbsp; &nbsp; Button:&nbsp; &nbsp; &nbsp; &nbsp; text: "Sensor 01"&nbsp; &nbsp; &nbsp; &nbsp; on_release:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; root.manager.current='grafico'其次,在您的Grafico班级中,您有一个build()从未被调用过的方法。如果您将其更改为:class Grafico(Screen):&nbsp; &nbsp; def build(self):&nbsp; &nbsp; &nbsp; &nbsp; box = BoxLayout()&nbsp; &nbsp; &nbsp; &nbsp; box.add_widget(FigureCanvasKivyAgg(plt.gcf()))&nbsp; &nbsp; &nbsp; &nbsp; return box到:class Grafico(Screen):&nbsp; &nbsp; def on_enter(self, *args):&nbsp; &nbsp; &nbsp; &nbsp; box = BoxLayout()&nbsp; &nbsp; &nbsp; &nbsp; box.add_widget(FigureCanvasKivyAgg(plt.gcf()))&nbsp; &nbsp; &nbsp; &nbsp; self.add_widget(box)我想你会得到想要的结果。关键是on_enter()在Grafico Screen显示时调用该方法。该方法是您的代码,但self.add_widget(box)添加了一个以将box加到屏幕上。有关更多信息,请参阅屏幕文档。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python