首页 > 解决方案 > 范围相关变量的问题

问题描述

各位程序员,大家好,我正在用 Python 开发一个简单的界面应用程序,它可以在访问数据库中轻松直观地输入库存表格。

我目前有一个功能如下:

def spawnerror(self, errormsg):
    self.running = False
    content = Button(text=errormsg)
    popup = Popup(title='ERROR!', content=content, auto_dismiss=False)
    content.bind(on_press=popup.dismiss)
    popup.open()

而且我已经完成了适当的错误处理,并且应用程序按预期使用了这个功能。例如,如果有人没有在必填字段中输入,它会调用此函数并生成一个带有错误的错误页面并通知用户。

我遇到的问题是,它需要将运行的类变量设置为 False,因为在主函数“提交”结束时它会检查它,如果 self.running == False,那么它需要跳过在访问数据库中执行数据输入。

为什么这个函数没有将运行的类变量设置为false?

标签: pythonpython-3.xkivy

解决方案


解决方案 - 使用 App.get_running_app()

在示例中,类属性running定义为 BooleanProperty。在spawnerror()函数中,它使用App.get_running_app()函数获取 App 类的实例,然后访问变量running.

笔记

如果runningspawnerror()函数和submit()函数在不同的类中,则计算出类的关系并在它们之间传递直接引用。

例子

主文件

from kivy.app import App
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty, ObjectProperty


class RootWidget(BoxLayout):
    instance = ObjectProperty(None)

    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)
        self.instance = App.get_running_app()
        self.spawnerror('Testing')

    def spawnerror(self, errormsg):
        self.instance.running = False
        content = Button(text=errormsg)
        popup = Popup(title='ERROR!', content=content, auto_dismiss=False)
        content.bind(on_press=popup.dismiss)
        popup.open()


class TestApp(App):
    running = BooleanProperty(True)

    def build(self):
        print("\nbuild:")
        self.display_attributes()
        return RootWidget()

    def on_stop(self):
        print("\non_stop:")
        self.display_attributes()

    def display_attributes(self):
        print("\tApp.running =", self.running)


if __name__ == "__main__":
    TestApp().run()

输出

图片01


推荐阅读