pythonvariableskivytextlabel

Text Label from variable value


Good afternoon, I have a problem, I would like to know if someone can help me: The aim is to project its value into the text of a label on the next screen.


from __future__ import print_function
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
# modolo data
from datetime import datetime
# tabela
from kivy.lang.builder import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.metrics import dp
from kivymd.app import MDApp
from kivymd.uix.datatables import MDDataTable
from kivy.properties import StringProperty

from plyer import notification

from kivy.uix.label import Label
from kivy.properties import StringProperty


from __future__ import print_function
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
# modolo data
from datetime import datetime
# tabela
from kivy.lang.builder import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.metrics import dp
from kivymd.app import MDApp
from kivymd.uix.datatables import MDDataTable
from kivy.properties import StringProperty

from plyer import notification

from kivy.uix.label import Label
from kivy.properties import StringProperty


KV = """
WindowManager:
    ScreenLogin:
        id: ScreenLogin
    ScreenPaginaInicial:
    PaginaEntradas:
        id: data_scr
    PaginaTipoEntrada:
    ScreenInicioProducao:  
        id: ScreenInicioProducao
    PaginaMovInterna:     
    PaginaMovExterna:      
    PaginaEditarArtigoOriginalInterna:
        id: PaginaEditarArtigoOriginalInterna
    PaginaEditarArtigoBob1Interna:
    PaginaEditarArtigoBob2Interna:
    PaginaEditarArtigoBob3Interna:
    PaginaEditarArtigoOriginalExterna:
    PaginaEditarArtigoBob1Externa:
    PaginaEditarArtigoBob2Externa:
    PaginaEditarArtigoBob3Externa:
<ScreenLogin>:
    name: "ScreenLogin"
    FloatLayout:
        canvas.before:
            Color:
                rgba: 1, 1, 1, 1
            Rectangle:
                pos: self.pos
                size: self.size
        Image:
            size_hint: 1, 1
            pos_hint: {"center_x": .5, "center_y": .85}
            source: 'G:\O meu disco\Gestao_Stocks\logo.png'
        GridLayout:
            cols: 1
            spacing: 5
            size_hint: 0.8, .6
            pos_hint: {"center_x": .5, "center_y": .4}
            Label:
                text: "Utilizador"
                size_hint_x: .3
                text_size: self.size
                halign: 'center'
                valign: 'middle'
                color: 0,0,0,1
                allow_copy: True
            TextInput:
                id: utilizador
                multiline: False
                halign: 'center'
                focus: True   
            Label:
                text: "Password"
                size_hint_x: .3
                text_size: self.size
                halign: 'center'
                valign: 'middle'
                color: 0,0,0,1
            TextInput:
                id: password
                multiline: False
                password: True
                password_mask: '#'
                halign: 'center'

            Label:
            Button:
                size_hint: 1., 1.
                text: "Login"
                on_release:
                    app.login()
                    app.root.current = "ScreenPaginaInicial"
                    root.manager.transition.direction = "left"
            Button:
                text: 'Sair da Aplicação'
                on_press: app.stop()                      
<ScreenPaginaInicial>:
    name: "ScreenPaginaInicial"
    FloatLayout:
        canvas.before:
            Color:
                rgba: 1, 1, 1, 1
            Rectangle:
                pos: self.pos
                size: self.size
        Image:
            size_hint: 1, 1
            pos_hint: {"center_x": .5, "center_y": .75}
            source: 'G:\O meu disco\Gestao_Stocks\logo.png'

        GridLayout:
            cols: 1
            spacing: 5
            size_hint: .7, .37
            pos_hint: {"center_x": .5, "center_y": .3}
            Label:
            Button:
                size_hint: 1., 1.
                text: "Armazém"
                on_release: 
                    app.change_screen('PaginaEntradas')
                    app.add_datatable()
            Label:
                text: utilizador.text
                size_hint_x: .3
                text_size: self.size
                halign: 'center'
                valign: 'middle'
                color: 0,0,0,1
            Button:
                size_hint: 1., 1.
                text: "Inicio da Produção"
                on_release:
                    app.root.current = "ScreenInicioProducao"
                    root.manager.transition.direction = "left"
            Button:
                text: 'Sair da Aplicação'
                on_press: app.stop()
"""




class ScreenLogin(Screen):
    pass


class ScreenPaginaInicial(Screen):
    pass


class PaginaEntradas(Screen):
    pass


class PaginaTipoEntrada(Screen):
    pass


class ScreenInicioProducao(Screen):
    pass


class PaginaMovExterna(Screen):
    pass


class PaginaMovInterna(Screen):
    pass


class PaginaEditarArtigoOriginalInterna(Screen):

    pass


class PaginaEditarArtigoBob1Interna(Screen):

    pass


class PaginaEditarArtigoBob2Interna(Screen):
    pass


class PaginaEditarArtigoBob3Interna(Screen):
    pass


class PaginaEditarArtigoOriginalExterna(Screen):
    tipo_movimentacao = StringProperty()
    pass


class PaginaEditarArtigoBob1Externa(Screen):
    pass


class PaginaEditarArtigoBob2Externa(Screen):
    pass


class PaginaEditarArtigoBob3Externa(Screen):
    pass


class WindowManager(ScreenManager):
    pass


class AppStocks(MDApp):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.data_tables = None

    def build(self):
        return Builder.load_string(KV)

    def add_datatable(self):
        SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

        def main():
            creds = None
            if os.path.exists('token.json'):
                creds = Credentials.from_authorized_user_file('token.json', SCOPES)
            # If there are no (valid) credentials available, let the user log in.
            if not creds or not creds.valid:
                if creds and creds.expired and creds.refresh_token:
                    creds.refresh(Request())
                else:
                    flow = InstalledAppFlow.from_client_secrets_file(
                        'client_secret.json', SCOPES)
                    creds = flow.run_local_server(port=0)
                # Save the credentials for the next run
                with open('token.json', 'w') as token:
                    token.write(creds.to_json())
            service = build('sheets', 'v4', credentials=creds)
            # ler informação do sheets
            sheet = service.spreadsheets()
            global dados_tabela
            dados_tabela = sheet.values().get(spreadsheetId='1TUGChfPE3A7QdGFonDlEUDrtQIC0m9z2XhR2NYxeQTQ',
                                              range='Folha1!A2:AC').execute()
            screenText = StringProperty(dados_tabela)
            dados_tabela1 = dados_tabela['values']
        if __name__ == '__main__':
            main()
        pass
        self.theme_cls.theme_style = "Light"
        self.data_tables = MDDataTable(
            use_pagination=True,
            check=True,
            size_hint=(1, 1),
            column_data=[
                ("[size=11]Bloco", dp(22)),
                ("[size=11]Estante", dp(15)),
                ("[size=11]Prateleira", dp(15)),
                ("[size=11]Descrição", dp(70)),
                ("[size=11]Quantidade de MP", dp(30)),
                ("[size=11]Bloco 1", dp(15)),
                ("[size=11]Estante 1", dp(15)),
                ("[size=11]Prateleira 1", dp(15)),
                ("[size=11]Produto Bobinado 1", dp(70)),
                ("[size=11]Qtd Produto Bobinado 1", dp(30)),
                ("[size=11]Bloco 2", dp(15)),
                ("[size=11]Estante 2", dp(15)),
                ("[size=11]Prateleira 2", dp(15)),
                ("[size=11]Produto Bobinado 2", dp(70)),
                ("[size=11]Qtd Produto Bobinado 2", dp(30)),
                ("[size=11]Bloco 3", dp(15)),
                ("[size=11]Estante 3", dp(15)),
                ("[size=11]Prateleira 3", dp(15)),
                ("[size=11]Produto Bobinado 3", dp(70)),
                ("[size=11]Qtd Produto Bobinado 3", dp(30)),
                ("[size=11]Tipo Doc", dp(30)),
                ("[size=11]Data Doc", dp(30)),
                ("[size=11]ID2", dp(30)),
                ("[size=11]Quantidade 2", dp(30)),
                ("[size=11]Anulado", dp(30)),
                ("[size=11]Imagem", dp(30)),
                ("[size=11]Unidade de Compra", dp(30)),
                ("[size=11]Preço/1", dp(30)),
                ("[size=11]__PowerAppsId__", dp(30)),
            ],
            row_data=dados_tabela["values"]
        )
        self.root.ids.data_scr.ids.data_layout.add_widget(self.data_tables)
        self.data_tables.bind(on_row_press=self.on_row_press)
        self.data_tables.bind(on_check_press=self.on_check_press)

    def on_row_press(self, instance_table, instance_row):
        '''Called when a table row is clicked.'''
        start_index, end_index = instance_row.table.recycle_data[instance_row.index]["range"]
        start_index = (start_index / 29) + 1
        start_index_l = int(start_index) + 1
        print("linha_selecionada")
        print(start_index_l)
        # print(instance_table, instance_row)
        global linha_selecionada
        linha_selecionada = start_index
        SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

        def main():
            creds = None
            if os.path.exists('token.json'):
                creds = Credentials.from_authorized_user_file('token.json', SCOPES)
            # If there are no (valid) credentials available, let the user log in.
            if not creds or not creds.valid:
                if creds and creds.expired and creds.refresh_token:
                    creds.refresh(Request())
                else:
                    flow = InstalledAppFlow.from_client_secrets_file(
                        'client_secret.json', SCOPES)
                    creds = flow.run_local_server(port=0)
                # Save the credentials for the next run
                with open('token.json', 'w') as token:
                    token.write(creds.to_json())
            service = build('sheets', 'v4', credentials=creds)
            # ler informação do sheets
            sheet = service.spreadsheets()

            dados_linha_clicada = sheet.values().get(spreadsheetId='1TUGChfPE3A7QdGFonDlEUDrtQIC0m9z2XhR2NYxeQTQ',
                                                     range='Folha1!A' + str(start_index_l) + ':AC' + str(
                                                         start_index_l)).execute()
            print('dados' + str(dados_linha_clicada))
            global dados_linha_clicada_valores
            dados_linha_clicada_valores = dados_linha_clicada['values']
            print("dados_linha_clicada")
            print(dados_linha_clicada_valores)

        if __name__ == '__main__':
            main()
        pass

    def on_check_press(self, instance_table, current_row):
        '''Called when the check box in the table row is checked.'''
        # print((instance_table, current_row))
        print("intervalo")
        print(current_row)

    def change_screen(self, screen: str):
        self.root.current = screen

    def login(self):
        global utilizador
        utilizador = self.root.get_screen('ScreenLogin').ids.utilizador.text
        print(utilizador)
        password = self.root.get_screen('ScreenLogin').ids.password.text
        # Implemesta regras para acesso. Exemplo:
        if utilizador == '1' and password == '1' \
                or utilizador == 'x' and password == 'y':
            # If modifying these scopes, delete the file token.json.
            SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

            def main():
                creds = None
                if os.path.exists('token.json'):
                    creds = Credentials.from_authorized_user_file('token.json', SCOPES)
                # If there are no (valid) credentials available, let the user log in.
                if not creds or not creds.valid:
                    if creds and creds.expired and creds.refresh_token:
                        creds.refresh(Request())
                    else:
                        flow = InstalledAppFlow.from_client_secrets_file(
                            'client_secret.json', SCOPES)
                        creds = flow.run_local_server(port=0)
                    # Save the credentials for the next run
                    with open('token.json', 'w') as token:
                        token.write(creds.to_json())
                service = build('sheets', 'v4', credentials=creds)
                # ler informação do sheets
                sheet = service.spreadsheets()
                dados_registo_logins = sheet.values().get(spreadsheetId='1YSFtrQIS3XfZHA7g67PxNaWcfF5uN_8ivrZvbqeZ2uU',
                                                          range='Folha1!A:B').execute()
                dados_registo_logins_valores = dados_registo_logins['values']
                n_linhas_registo_logins = len(dados_registo_logins_valores)
                print("nlinhas")
                print(n_linhas_registo_logins)
                linha_adicionar_dados_registo_logins = str(n_linhas_registo_logins + 1)
                adicionar_registo_logins = [
                    [utilizador, password, str(datetime.now())],
                ]
                # Escrever informação no sheets
                sheet = service.spreadsheets()
                dados_adicionar_logins = sheet.values().update(
                    spreadsheetId='1YSFtrQIS3XfZHA7g67PxNaWcfF5uN_8ivrZvbqeZ2uU',
                    range='Folha1!A' + linha_adicionar_dados_registo_logins, valueInputOption="USER_ENTERED",
                    body={"values": adicionar_registo_logins}).execute()
                notification.notify(title='Login', message='Login efetuado com sucesso!')

            if __name__ == '__main__':
                main()
            pass
        else:
            # If modifying these scopes, delete the file token.json.
            SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

            def main():
                creds = None
                if os.path.exists('token.json'):
                    creds = Credentials.from_authorized_user_file('token.json', SCOPES)
                # If there are no (valid) credentials available, let the user log in.
                if not creds or not creds.valid:
                    if creds and creds.expired and creds.refresh_token:
                        creds.refresh(Request())
                    else:
                        flow = InstalledAppFlow.from_client_secrets_file(
                            'client_secret.json', SCOPES)
                        creds = flow.run_local_server(port=0)
                    # Save the credentials for the next run
                    with open('token.json', 'w') as token:
                        token.write(creds.to_json())
                service = build('sheets', 'v4', credentials=creds)
                # ler informação do sheets
                sheet = service.spreadsheets()
                dados_registo_logins_erro = sheet.values().get(
                    spreadsheetId='1YSFtrQIS3XfZHA7g67PxNaWcfF5uN_8ivrZvbqeZ2uU',
                    range='Folha1!A:B').execute()
                dados_registo_logins_erro_valores = dados_registo_logins_erro['values']
                n_linhas_registo_logins_erro = len(dados_registo_logins_erro_valores)
                linha_adicionar_dados_registo_logins_erro = str(n_linhas_registo_logins_erro + 1)
                adicionar_registo_logins_erro = [
                    ['ERRO!' + utilizador, 'ERRO!' + password, str(datetime.now())],
                ]
                # Escrever informação no sheets
                sheet = service.spreadsheets()
                dados_adicionar_registo_logins_erro = sheet.values().update(
                    spreadsheetId='1YSFtrQIS3XfZHA7g67PxNaWcfF5uN_8ivrZvbqeZ2uU',
                    range='Folha1!A' + linha_adicionar_dados_registo_logins_erro, valueInputOption="USER_ENTERED",
                    body={"values": adicionar_registo_logins_erro}).execute()
                notification.notify(title='Login', message='Erro!')

            if __name__ == '__main__':
                main()
            pass

I have here part of my code, hope it's enough.

In short, I want to use the "utilizador" variable value, and insert its text inside a lable, I tried:

Label:
      text: utilizador.text

I've been looking for a solution for a long time, I've read everything but I can't solve it. My difficulty is that I have several screens, inside one of them I define a variable.


Solution

  • Your posted code is not a minimal reproducible example, but here is an example of one way to do what you want:

    from kivy.app import App
    from kivy.lang import Builder
    from kivy.uix.screenmanager import ScreenManager, Screen
    
    
    class WindowManager(ScreenManager):
        pass
    
    
    class ScreenLogin(Screen):
        pass
    
    
    class ScreenPaginaInicial(Screen):
        pass
    
    kv = '''
    WindowManager:
        ScreenLogin:
            id: ScreenLogin
        ScreenPaginaInicial:
            id: ScreenPaginaInicial
        
    <ScreenLogin>:
        name: 'ScreenLogin'
        BoxLayout:
            TextInput:
                id: utilizador
                on_text: root.manager.ids.ScreenPaginaInicial.ids.lab.text=self.text  # update Label whenever text changes
            Button:
                text: 'other Screen'
                on_release: root.manager.current='ScreenPaginaInicial'
        
    <ScreenPaginaInicial>:
        name: 'ScreenPaginaInicial'
        BoxLayout:
            Label:
                id: lab
                text: 'Abba'
            Button:
                text: 'other Screen'
                on_release: root.manager.current='ScreenLogin'
    '''
    
    
    class TestApp(App):
        def build(self):
            return Builder.load_string(kv)
    
    TestApp().run()