Home > database >  Modify variables within Python through a button in Kivy
Modify variables within Python through a button in Kivy

Time:07-17

I have an application that at a certain point needs to check if a variable within its Python code has one value or another, and also requires a button capable of changing that variable from one value to another to also save that information in a text file and that the variable loads it the next time the application is started.

Here I prepared a small program to exemplify what I am looking for:

import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang.builder import Builder
from kivy.core.window import Window

Window.size=(200,200)

data=open('data.txt','r') #Let's say there is a text file called "data" that contains the number 0

Builder.load_string("""
<Screen>
    BoxLayout:
        orientation:'vertical'
        size:root.width,root.height
        Label:
            text:'Switch On' if app.var==1 else 'Switch Off' #Initially then the label should say "Switch Off"
        Button:
            text:'Switcher'
            on_release: #Change app.var from 0 to 1 or from 1 to 0
""")

class Screen(Widget):
    pass

class App(App):
    def build(self):
        self.var=data.read()
        #Save the changes made by the Button 
        return Screen()

if __name__=='__main__':
    App().run()

How can I do this or something similar? A better and simpler way?

CodePudding user response:

You should define a function and bind it to a button. The documentation can really help you here! you can bind your function using my_button.bind(on_press=on_button_click) where:

def on_button_click():
    this.my_var  = 1

Let me know if you think the documentation is unclear!

  • Related