python - 范围相关变量的问题
问题描述
各位程序员,大家好,我正在用 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?
解决方案
解决方案 - 使用 App.get_running_app()
在示例中,类属性running
定义为 BooleanProperty。在spawnerror()
函数中,它使用App.get_running_app()
函数获取 App 类的实例,然后访问变量running
.
笔记
如果running,spawnerror()函数和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()
输出
推荐阅读
- docker - 带有 rsync 的 docker-machine
- kubernetes - allow access to all resources on kubernetes cluster except get nodes
- c++ - How do you check if a file exists in C++ without opening the file?
- spring-statemachine - Spring State Machine - Attaching static data to states
- html - How do I change the appearance of my web app on form submit?
- php - 当我使用 auto_prepend_file 时,$_SERVER['HTTP_USER_AGENT'] 不起作用
- excel - 在 Excel 中提取两个字符之间的特定文本字符串部分
- git - 如何诊断 git cat-file 声称缺少对象?
- c++ - 带有 std::thread 类的 C++ 堆栈泄漏
- java - 使用 @EmbeddedId 生成无效 SQL 的 CriteriaQuery selectDistinct