ATEK0
ATEK0

Reputation: 92

Passing a variable from a function to be acessible in other function [Python]

I'm recently new in the python world, and I'm struggling with one problem...

I'm doing an app that connects to a database in the raspberry pi (which is always changing its ip, and android phones can't solve its hostname, that's why I need to specify the address).

I'm currently using Python 3.9 and Kivy 2.0.0.

I want that those 2 variables (mydb and mycursor) inside the variavel function to be accessible inside the other functions... Is there any way for me to do this?

Main.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.properties import StringProperty
from kivy.uix.label import Label
from kivy.uix.popup import Popup
import mysql.connector

class MainWidget2(BoxLayout):

    server_connect = StringProperty("not_connected.png")
    debug_net = StringProperty()
    hosts = StringProperty()
    input_text = StringProperty()
    def variavel(self, widget):
        self.hosts= widget.text
        widget.text = ""
        try:
            mydb = mysql.connector.connect(host=str(self.hosts), user="client", passwd="", database="skye_pap")
            mycursor = mydb.cursor()
            self.server_connect = 'connected.png'
        except Exception as a:
            self.debug_net = str(a)
            self.server_connect = 'not_connected.png'

    def frente(self):
        try:
            mydb = mysql.connector.connect(host=str(self.hosts), user="client", passwd="afonso11", database="skye_pap")
            mycursor = mydb.cursor()
            mycursor.execute('UPDATE car_controll SET motor=1')
            mydb.commit()
        except Exception as b:
            
            pass
    def tras(self):
        mydb = mysql.connector.connect(host=str(self.ids["input"].text), user="client", passwd="afonso11", database="skye_pap")
        mycursor = mydb.cursor()
        try:
            mycursor.execute('UPDATE car_controll SET motor=-1')
            mydb.commit()
        except Exception as b:
            pass
    def esq(self):
        try:
            self.mycursor.execute('UPDATE car_controll SET servo=1')
            self.mydb.commit()
        except Exception as b:
            pass
    def dir(self):
        try:
            self.mycursor.execute('UPDATE car_controll SET servo=2')
            self.mydb.commit()
        except Exception as b:
            pass
    def meio(self):
        try:
            self.mycursor.execute('UPDATE car_controll SET servo=0')
            self.mydb.commit()
        except Exception as b:
            pass
    def meio_motor(self):
        try:
            self.mycursor.execute('UPDATE car_controll SET motor=0')
            self.mydb.commit()
        except Exception as b:
            pass
    def lights_on(self, onemore, state):
        if state == "down":
            print("on")
            try:
                self.mycursor.execute('UPDATE car_controll SET luz=1')
                self.mydb.commit()
            except Exception as z:
                pass
        else:
            print("off")
            try:
                self.mycursor.execute('UPDATE car_controll SET luz=0')
                self.mydb.commit()
            except Exception as z:
                pass
        

class skye(App):
    def build(self):
        self.icon = "logoapp.png"

skye().run()

skye.kv

MainWidget2:

<MainWidget2>:
    GridLayout:
        cols:3
        GridLayout:#botoes esquerda
            padding: ("50dp","30px","0px","0px")
            pos: self.parent.pos
            cols: 3
            Button:
                text: "0"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0
                    
            Button:
                text: "B1"
                size_hint: None,None
                size: "100dp", "100dp"
                background_normal: 'desligado.png'
                background_down: 'ligado2.png'
                on_press: root.frente()
                on_release: root.meio_motor()

            Button:
                text: "0"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0

            Button:
                text: "B2"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0
        
            Button:
                text: "0"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0
                
            Button:
                text: "B3"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0


            Button:
                text: "0"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0
                
            Button:
                text: "B4"
                size_hint: None,None
                on_press: root.tras()
                on_release: root.meio_motor()
                size: "100dp", "100dp"
                background_normal: 'desligado.png'
                background_down: 'ligado2.png'

            Button:
                text: "0"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0

        GridLayout:
            cols: 1
        
            Image:
                source: root.server_connect
                size_hint: .8, .8
                id:server_status
            FloatLayout:
                ToggleButton:
                    pos_hint: {'center_x': .5, 'center_y': .5}
                    id: luzes_toggle
                    size_hint: None, None
                    size: "100dp", "100dp"
                    background_normal: 'luz_desligada.png'
                    background_down: 'luz_ligada.png'
                    on_state: root.lights_on(self, self.state)
                
            Label:
                text: root.debug_net
            TextInput:
                id: input
                multiline: False
                on_text_validate: root.variavel(self)
                text: root.input_text
            Label:
                text: root.hosts
            Button:
                text:"Falar"
            Label:
                text: "Luzes:"
            
        GridLayout:#botoes direita
            cols: 3
            padding: ("0dp","30px","50px","0px")
            Button:
                text: "0"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0
                
                    
            Button:
                text: "B1"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0

            Button:
                text: "0"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0

            Button:
                text: "B2"
                size_hint: None,None
                size: "100dp", "100dp"
                background_normal: 'desligado.png'
                background_down: 'ligado2.png'
                on_press: root.esq()
                on_release: root.meio()
        
            Button:
                text: "0"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0
                
            Button:
                text: "B3"
                size_hint: None,None
                size: "100dp", "100dp"
                background_normal: 'desligado.png'
                background_down: 'ligado2.png'
                on_press: root.dir()
                on_release: root.meio()

            Button:
                text: "0"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0
                
            Button:
                text: "B4"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0
                
            Button:
                text: "0"
                size_hint: None,None
                size: "70dp", "70dp"
                disabled: True
                opacity: 0


            
    

Upvotes: 0

Views: 78

Answers (3)

em_bis_me
em_bis_me

Reputation: 388

Create class variables inside the class Mainwidget2 - lets name them: class_my_db, class_my_cursor.

class MainWidget2(BoxLayout):

server_connect = StringProperty("not_connected.png")
debug_net = StringProperty()
hosts = StringProperty()
input_text = StringProperty()
class_my_db = '' //New Class Variable to hold my_db
class_my_cursor = '' //New Class Variable to hold my_cursor

Now you can set the class variables their value after reading through mysql.

def variavel(self, widget):
    self.hosts= widget.text
    widget.text = ""
    try:
        mydb = mysql.connector.connect(host=str(self.hosts), user="client", passwd="", database="skye_pap")
        self.class_my_db = mydb //assigning mydb to the class variable
        mycursor = mydb.cursor()
        self.class_my_cursor = mycursor //assigning mydb to the class variable
        self.server_connect = 'connected.png'
    except Exception as a:
        self.debug_net = str(a)
        self.server_connect = 'not_connected.png'

Now you can access the class variables in all other functions using self operator. self.class_my_db and self.class_my_cursor would suffice that.

Upvotes: 0

AbbeGijly
AbbeGijly

Reputation: 1211

To promote method-scoped variables to be available to other class methods, add them to self:

self.mydb = mysql.connector.connect(...[stuff]...)
self.mycursor = self.mydb.cursor()

then replace all references to mydb with self.mydb and mycursor with self.mycursor. Those variables will be accessible from other methods of the same class.

Upvotes: 0

You should add self. before every variable which you want to be accessible from every method in the object.

For example make every mydb variable to self.mydb ,and mycursor to self.mycursor.

Upvotes: 1

Related Questions