Как передать значение из одного класса в другой в KivyMD
Как в Class2 передать на печать root.ids.user.text и root.ids.password.text? Помогите внести изменения в код
main.py
from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivy.storage.jsonstore import JsonStore
from kivymd.app import MDApp
from kivymd.uix.scrollview import MDScrollView
from kivy.config import Config
from kivymd.uix.textfield import MDTextField
from class2 import Class2
class ContentNavigationDrawer(MDScrollView):
screen_manager = ObjectProperty()
nav_drawer = ObjectProperty()
class Main(MDApp):
def build(self):
Config.read("myApp.ini")
self.theme_cls.theme_style = "Dark"
self.theme_cls.primary_palette = "BlueGray"
return Builder.load_file('file.kv')
def on_start(self):
print("\non_start:")
store = JsonStore('myBackup.json')
if store.count() > 0:
for key in store:
print("\tid = {0}, obj = {1}".format(key, self.root.ids[key]))
if isinstance(self.root.ids[key], MDTextField):
self.root.ids[key].text = store.get(key)['text']
print("\t\ttext = ", self.root.ids[key].text)
def on_stop(self):
print("\non_stop:")
store = JsonStore('myBackup.json')
for key in self.root.ids:
if isinstance(self.root.ids[key], MDTextField):
print("\tid = {0}, text = {1}".format(key, self.root.ids[key].text))
store.put(key, text=self.root.ids[key].text)
def logger(self):
self.root.ids.scr1_label.text = f'Привет {self.root.ids.user.text}!'
def authorization(self):
self.thread_1 = Class2()
self.thread_1.start()
Main().run()
class2.py
import threading
class Class2(threading.Thread):
def __init__(self, parent=None):
super(Class2, self).__init__(parent)
self.parent = parent
def run(self):
print(f'Логин: {self.parent.root.ids.user.text}')
print(f'Пароль: {self.parent.root.ids.password.text}')
file.kv
<ContentNavigationDrawer>
MDList:
OneLineListItem:
text: "Окно 1"
on_press:
root.nav_drawer.set_state("close")
root.screen_manager.current = "scr 1"
OneLineListItem:
text: "Окно 2"
on_press:
root.nav_drawer.set_state("close")
root.screen_manager.current = "scr 2"
MDScreen:
MDTopAppBar:
pos_hint: {"top": 1}
md_bg_color: "blue"
elevation: 4
left_action_items: [["menu", lambda x: nav_drawer.set_state("open")]]
MDNavigationLayout:
MDScreenManager:
id: screen_manager
MDScreen:
name: "scr 1"
MDBoxLayout:
size_hint: None, None
size: 300, 400
pos_hint: {"center_x": 0.5, "center_y": 0.5}
elevation: 10
padding: 25
spacing: 25
orientation: 'vertical'
MDLabel:
id: scr1_label
text: "Окно 1"
font_size: 40
halign: "center"
size_hint_y: None
height: self.texture_size[1]
padding_y: 15
MDTextField:
id: user
text: ""
hint_text: "имя пользователя"
icon_right: "account"
size_hint_x: None
width: 300
font_size: 18
pos_hint: {"center_x": 0.5}
mode: "round"
MDTextField:
id: password
text: ""
hint_text: "пароль"
icon_right: "eye"
size_hint_x: None
width: 300
font_size: 18
pos_hint: {"center_x": 0.5}
#password: True
mode: "round"
MDLabel:
id: scr1_label_down
text: ""
font_size: 20
halign: "center"
size_hint_y: None
height: self.texture_size[1]
padding_y: 15
MDRoundFlatButton:
text: "LOGIN"
font_size: 12
pos_hint: {"center_x": 0.5}
on_press: app.authorization(), app.logger()
Widget:
size_hint_y: None
height: 10
MDScreen:
name: "scr 2"
MDBoxLayout:
size_hint: None, None
size: 300, 400
pos_hint: {"center_x": 0.5, "center_y": 0.5}
elevation: 10
padding: 25
spacing: 25
orientation: 'vertical'
MDLabel:
id: scr2_label
text: "Окно 2"
font_size: 40
halign: "center"
size_hint_y: None
height: self.texture_size[1]
padding_y: 15
MDTextField:
id: key
hint_text: ""
size_hint_x: None
width: 300
font_size: 18
pos_hint: {"center_x": 0.5}
mode: "round"
Widget:
size_hint_y: None
height: 80
MDNavigationDrawer:
id: nav_drawer
radius: (0, 16, 16, 0)
ContentNavigationDrawer:
screen_manager: screen_manager
nav_drawer: nav_drawer
Ответы (2 шт):
Благодаря тому, что в данном коде используется .json файл, я пошел обходным путем и получил значения напрямую из .json файла. И все же, было бы полезно узнать как получать значения из другого класса. Быть может в Kivy есть специальные механизмы для этого....
class2.py
import json
import threading
class Class2(threading.Thread):
def __init__(self, parent=None):
super(Class2, self).__init__(parent)
self.parent = parent
def run(self):
with open('myBackup.json') as f:
data = json.load(f)
print(data)
login = data['user']['text']
print(login)
password = data['password']['text']
print(password)
Используй для этого StringProperty (kivy.properties). Для этого ты можешь создать отдельный объект, и заранее создать в нем 2 StringProperty, потом их использовать между скринами, и при переходе на новый экран сохранять инпут пользователя для отображения на втором экране.
