How to set existing text from a variable within a function? Python Kivy

雨燕双飞 提交于 2019-12-11 20:29:55

问题


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.

The loginfo needs to be within a function because I am using the kivy's Clock to re-read the log file.

Python file:

class Tasks(Screen):
    logginfo = ObjectProperty()

    def reset_text(dt):
        with open('logtest.log', 'r') as file:
            loginfo = file.read()

    Clock.schedule_once(reset_text, -1)

Kivy file:

<Tasks>:
    name: 'task'
    logginfo: logginfo
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "TASKS"

        TextInput:
            id: logginfo
            text: root.loginfo

The problem started occurring when I created the reset_text(dt) function and kivy.clock. Without the function, and just the contents of it, the textinput box displays the logtest.log file's contents correctly.

When I run the script, it gives me AttributeError: 'NoneType' object has no attribute 'replace'. I'm confused and stuck, any help would be appreciated. Thanks in advance.


回答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


来源:https://stackoverflow.com/questions/54597139/how-to-set-existing-text-from-a-variable-within-a-function-python-kivy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!