Issue
I'm having an issue understanding how to update a label text in my popup from my main class.
I'm receiving some data from a server in a text file and I want to display it on the popup when it's open.
In my main class, a physical button is declared which when pressed, triggers a function that saves each line of the text file a variable (contents). I want my label text located in the popup to be updated with this string variable 'contents'.
I understand that the problem is that I'm trying to update the class itself rather then the instance of the popup but i can't figure out how to fix it.
#test_kivy.py
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.clock import Clock
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.popup import Popup
import RPi.GPIO as GPIO
global pin
pin = 10 #Button pin
GPIO.setmode(GPIO.BOARD) # Setting pin board pin mode
GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) #sets Pis internal resistors to pull-up
#Popup class
class Txt_Pop(FloatLayout):
pass
#Main class
class Test(Screen):
def __init__(self, **kwargs):
super(Test, self).__init__(**kwargs)
# Scheduling the start of the program, giving time to the GUI to initialise
Clock.schedule_once(self.button_state, 4)
# Checking if button is pressed (1 = not pressed, 0 = pressed)
def button_state(self,dt):
#Button not pressed so do nothing
while GPIO.input(pin) == 1:
GPIO.input(pin)
#Button pressed so trigger functions
if GPIO.input(pin) == 0:
self.txt_to_print()
Clock.schedule_once(self.open_popup, 1)
# Storing every lines of the txt file in a variable
def txt_to_print(self):
global contents
with open("analysis.txt") as f:
contents = f.read()
f.close()
return contents
# Opening popup with the analysis.txt printed
def open_popup(self,dt):
#This is what Im not managing to do
self.ids.pop_label.text = contents
showing = Txt_Pop()
global pop_Wind
pop_Wind = Popup(title="Here is the analysis", content=showing, size_hint=(None,None), size=(400,400))
pop_Wind.open()
class WindowManager(ScreenManager):
pass
class TestGui(App):
def build(self):
self.load_kv('test_kivy.kv')
return Test()
if __name__ == "__main__":
TestGui().run()
And the kivy file:
#text_kivy.kv
# WindowManager:
# Test:
# Txt_Pop:
<Test>:
size: root.width, root.height
id: main_menu
FloatLayout:
Label:
id : lab
text: "Press Button to display analysis"
pos_hint: {"x":0,"top":1}
<Txt_Pop@Popup>:
Label:
id : pop_label
font_size: 12
text: ""
pos_hint: {"x":0,"top":1.2}
Thank you for any help.
Solution
If you define your Txt_Pop
class as:
class Txt_Pop(FloatLayout):
text = StringProperty('')
and use the text
property in the kv
:
<Txt_Pop@Popup>:
Label:
id : pop_label
font_size: 12
text: root.text
pos_hint: {"x":0,"top":1.2}
Then you can set the text that gets shown in the Popup
using:
showing = Txt_Pop()
showing.text = self.txt_to_print()
Answered By - John Anderson Answer Checked By - Mary Flores (WPSolving Volunteer)