如何在kivy中引用另一个类方法
Posted
技术标签:
【中文标题】如何在kivy中引用另一个类方法【英文标题】:How to refer to another class method in kivy 【发布时间】:2021-04-09 03:24:00 【问题描述】:我正在尝试制作一个应用程序。单击屏幕右下角的按钮会出现一个对话窗口(弹出窗口)。在“完成”上单击弹出窗口关闭(close_dialog
方法),预计会出现一个新的列表项。
不幸的是,错误发生在“完成”点击:
AttributeError: 'DialogContent' object has no attribute 'get_screen'
能否请您告诉我为什么会发生错误以及如何解决?
我想这是因为DialogContent
类继承自BoxLayout
(而不是Screen
),但我不知道如何解决。
代码.py:
from kivy.lang import Builder
from kivy.core.window import Window
from kivymd.app import MDApp
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.scrollview import ScrollView
from kivymd.uix.button import MDFlatButton
from kivymd.uix.dialog import MDDialog
from kivymd.uix.textfield import MDTextField
from kivy.uix.textinput import TextInput
from kivy.uix.screenmanager import Screen, ScreenManager
from kivymd.uix.list import TwoLineAvatarListItem
Window.size = (288, 511)
class GroupScreen(Screen):
pass
class DialogContent(BoxLayout):
pass
class MainScreen(Screen):
dialog = None
def show_dialog(self, *args):
'''
Create group creation popup
'''
if not self.dialog:
self.dialog = MDDialog(
title="Create new group",
type="custom",
content_cls=DialogContent(),
auto_dismiss=False
)
self.dialog.open()
def close_dialog(self, *args):
'''
Close popup on Done click
'''
self.dialog.dismiss()
self.new_window()
def new_window(self, *args):
'''
Create new group button
'''
mylist = TwoLineAvatarListItem(text = self.dialog.content_cls.textfield.text,
secondary_text = "1,2,3...")
self.mdlist.add_widget(mylist)
class test2App(MDApp):
def build(self):
sm = ScreenManager()
sm.add_widget(MainScreen(name='main'))
sm.add_widget(GroupScreen(name='group'))
scroll = ScrollView()
return sm
if __name__ == '__main__':
test2App().run()
代码.kv:
ScreenManager:
MainScreen:
GroupScreen:
<DialogContent>:
textfield: textfield
orientation: "vertical"
spacing: "12dp"
size_hint_y: None
height: "120dp"
MDTextField:
id: textfield
hint_text: "Group name"
MDFlatButton:
id: btn1
text: "Done"
text_color: self.theme_cls.primary_color
on_release: root.get_screen['main'].close_dialog()
<MainScreen>:
name: 'main'
mdlist: mdlist
FloatLayout:
size_hint: 1, 0.89
ScrollView:
MDList:
id: mdlist
MDFloatingActionButton:
pos_hint: 'right': 0.95, 'y': 0.05
icon: "android"
theme_text_color: "Custom"
text_color: app.theme_cls.primary_color
on_release:
root.show_dialog()
<GroupScreen>:
name: 'group'
MDLabel:
text: 'Welcome'
halign: 'center'
MDRectangleFlatButton:
text: 'Back'
pos_hint: 'center_x': 0.5, 'center_y': 0.3
on_release: root.manager.current = 'main'
【问题讨论】:
【参考方案1】:变化:
on_release: root.get_screen['main'].close_dialog()
到:
on_release: app.root.get_screen('main').close_dialog()
app.root
为您提供对app
的root
小部件的引用,即ScreenManager
。然后你可以使用get_screen('main')
访问主Screen
并调用它的close_dialog()
方法。
【讨论】:
以上是关于如何在kivy中引用另一个类方法的主要内容,如果未能解决你的问题,请参考以下文章
带有软删除的 Spring Boot GET 方法如何在服务 impl 中添加另一个异常