Skip to content Skip to sidebar Skip to footer

How To Set Existing Text From A Variable Within A Function? Python Kivy

I created a function that opens a log file, and saves it to a variable named loginfo. In my kivy file, I have a TextInput widget. I tried setting the existing text: to root.loginfo

Solution 1:

Here is a complete example to do what you want to do. You'll have to modify it to integrate it with your code, but my intention here was to show you the proper way to achieve this and let your work with it yourself.

Note how I'm using Clock.schedule_interval instead of schedule once. The 1 in the schedule_interval is the time between calling the self.reset_text function in seconds. Note how in the reset_text function I can refer to my base widget in my kv file using self.root (the GridLayout), then I can get the TextInput (since I gave it an id) by doing self.root.ids['my_text_input']

main.py

from kivy.app import App
from kivy.clock import Clock
from kivy.lang import Builder

GUI = Builder.load_file("main.kv")

class MainApp(App):
    def build(self):
        Clock.schedule_interval(self.reset_text, 1) # Check if log has changed once a second
        return GUI

    def reset_text(self, *args):
        with open("logtest.log", "r") as f:
            self.root.ids['my_text_input'].text = f.read()

MainApp().run()

main.kv

GridLayout:
    # This is the 'root' widget when referenced in python file
    cols: 1
    TextInput:
        id: my_text_input

Post a Comment for "How To Set Existing Text From A Variable Within A Function? Python Kivy"