This seems like a pretty simple issue but I just can't figure it out. I'm using Kivy with Python 2.7. How do I call the NewFunction() function from inside build(self)?
from kivy.core.window import Window
Window.clearcolor = (1, 1, 1, 1)
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.anchorlayout import AnchorLayout
class TestApp(App):
def build(self):
anchor_layout = AnchorLayout(anchor_x='center', anchor_y='top')
lblInitiate = Label(text='[color=1f358e][font=tahoma]Hello World[/color][/font]', markup = True, font_size='20sp')
lblInitiate.size_hint = (0.1, 0.1)
anchor_layout.add_widget(lblInitiate)
return anchor_layout
NewFunction()
def NewFunction():
lblOne = Label(text="[color=1f358e]Test[/color]")
return lblOne
if __name__ == '__main__':
TestApp().run()
Just do:
self.NewFunction()
but note that you need to declare NewFunction like this:
def NewFunction(self): <--- self
as it's a method of your class.
Related
I am newbies to programming, just picking up python. I have a very simple program which is showing a popup message, and it seems OK:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.popup import Popup
class t6App(App):
def build(self):
lb = Label(text="Welcome Here",size_hint=(1,0.8),pos_hint={'left':1,'top':1})
bt = Button(text="Press Me", size_hint=(1,0.1),pos_hint={'left':1,'x':0})
fl = FloatLayout()
fl.add_widget(lb)
fl.add_widget(bt)
cp = Popup(title='Guys', content=fl)
return cp
t6App().run()
Then I wanted to modify it, and add more things to it, the popup didn't show then: (2 programs always the same)
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.popup import Popup
class CustPop(Popup):
def build(self):
lb = Label(text="Welcome Here",size_hint=(1,0.8),pos_hint={'left':1,'top':1})
bt = Button(text="Press Me", size_hint=(1,0.1),pos_hint={'left':1,'x':0})
fl = FloatLayout()
fl.add_widget(lb)
fl.add_widget(bt)
cp = Popup(title='Guys', content=fl)
return cp
class t6App(App):
def build(self):
cp1 = CustPop()
return cp1
t6App().run()
The codes do run, but it seems like the layout /button /label in CustPop() can't be accessed (became a blank popup). My question is why and how to make it work?
Thx guys. I am appreciated.
You have defined a build() method in your CustPop, but unlike the App class, that build() method is not automatically called. You should put that code (with a couple minor changes) in the __init__() method.
class CustPop(Popup):
def __init__(self, **kwargs):
super(CustPop, self).__init__(**kwargs)
lb = Label(text="Welcome Here", size_hint=(1, 0.8), pos_hint={'left': 1, 'top': 1})
bt = Button(text="Press Me", size_hint=(1, 0.1), pos_hint={'left': 1, 'x': 0})
fl = FloatLayout()
fl.add_widget(lb)
fl.add_widget(bt)
# cp = Popup(title='Guys', content=fl)
self.title = 'Guys'
self.content = fl
Hello i'm relatively new to python and kivy and I've been looking around but i cant quite find the answer, i'm trying to make a hub where I can display live data from my rasberry-pi. I made a clock widget using a Label, and it updates time, but when i try to add my CPU usage only one label shows up. I thought the widgets might be covering each other but I used size_hint and it wont help. When i run the code below, only the timex will show up and only if i delete the Clock.schedule_interval(display32.timex, (1)) will the *updatex * display.
Thanks alot for the help
from kivy.app import App
from kivy.uix.label import Label
from kivy.clock import Clock
from kivy.uix.floatlayout import FloatLayout
import psutil
from kivy.lang import Builder
import time
class Display(Label, FloatLayout):
def __init__(self):
super(Display, self).__init__()
def updatex(self, *args):
self.cpu2 = psutil.cpu_percent()
self.text=str(self.cpu2)
self.size_hint=(.5, .25)
self.pos=(500, 500)
self.texture_size=(0.1,0.1)
def timex(self, *args):
self.time2 = time.asctime()
self.text = str(self.time2)
self.size_hint = (.5, .25)
self.pos = (30, 500)
self.size_hint=(0.1,0.1)
class TimeApp(App):
def build(self):
display32 = Display()
Clock.schedule_interval(display32.updatex, (1))
Clock.schedule_interval(display32.timex, (1))
return display32
if __name__ == "__main__":
TimeApp().run()
Instead of passing both labels to the clock, you can define a widget, add both labels and start the clock on the widget.
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.clock import Clock
import psutil
import time
class Display(Widget):
def draw(self, *args):
self.clear_widgets()
self.add_widget(Label(text=str(psutil.cpu_percent()), pos=(500, 500)))
self.add_widget(Label(text=str(time.asctime()), pos=(30, 500)))
class TimeApp(App):
def build(self):
display32 = Display()
Clock.schedule_interval(display32.draw, 1)
return display32
if __name__ == '__main__':
TimeApp().run()
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.core.window import Window
from kivy.uix.scrollview import ScrollView
from kivy.effects.scroll import ScrollEffect
from kivy.uix.widget import Widget
from kivy.uix.button import Button
class BSGameMain:
def sas(self):
# blmain.remove_widget(scrlFBtns)
self.scrlFBtns.remove_widget(blbtns)
blmain = BoxLayout(orientation = 'vertical') # MainBoxLayout init
scrlFBtns = ScrollView(effect_cls = 'ScrollEffect')
blbtns = BoxLayout(
orientation = 'vertical',
size_hint_y = None
) # BoxLayout for buttons
blbtns.bind(minimum_height = blbtns.setter('height'))
scrlFBtns.add_widget(blbtns)
for i in range (2):
blbtns.add_widget(Button(
text='asd',
size_hint_y = None,
height = 40,
on_press = sas
))
lblmain = Label(text = 'asd')
blmain.add_widget(lblmain)
blmain.add_widget(scrlFBtns)
class BSApp(App):
def build(self):
game = BSGameMain()
return game.blmain
if __name__ == "__main__":
BSApp().run()
AttributeError 'Button' object has no attribute scrlFBtn. What is the problem? I'm trying to make it so that when you clicked, the screen was cleared (Widget was deleted). Рelp me please =)
Your code has several errors and bad programming practices:
if you declare variables that are inside a class and outside any method of the class will be class variables and not attributes of the class, so it is not a good practice to do so if you want to use later self, all that code must be within a method of a class.
on_someproperty wait as parameter a function that receives parameters, in your case sas() does not receive them so the solution is to use a lambda method.
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.scrollview import ScrollView
from kivy.effects.scroll import ScrollEffect
from kivy.uix.button import Button
class BSGameMain:
def __init__(self):
self.blmain = BoxLayout(orientation = 'vertical') # MainBoxLayout init
self.scrlFBtns = ScrollView(effect_cls = 'ScrollEffect')
self.blbtns = BoxLayout(
orientation = 'vertical',
size_hint_y = None )
self.blbtns.bind(minimum_height = self.blbtns.setter('height'))
self.scrlFBtns.add_widget(self.blbtns)
for i in range(2):
self.blbtns.add_widget(Button(
text='asd',
size_hint_y = None,
height = 40,
on_press = lambda *args: self.sas()))
lblmain = Label(text = 'asd')
self.blmain.add_widget(lblmain)
self.blmain.add_widget(self.scrlFBtns)
def sas(self):
self.scrlFBtns.remove_widget(self.blbtns)
class BSApp(App):
def build(self):
game = BSGameMain()
return game.blmain
if __name__ == "__main__":
BSApp().run()
I'm having issues with parsing a data structure to a widget in Kivy, which would then access the structure and be able to show a value on the screen be updated continuously via a clock interval (not sure of a better to do this yet).
I have highlighted the issues in the (non-working) code below:
main.py
from kivy.app import App
from test import TestWidget
class TestApp(App):
def build(self):
testStructTable = {'randomVal1': 1, 'testVal': 2, 'randomVal2': 3}
# Issue here parsing the table like this?
return TestWidget(testStructTable)
if __name__ == '__main__':
TestApp().run()
test.py
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.relativelayout import RelativeLayout
from kivy.properties import NumericProperty
class TestWidget(RelativeLayout):
def __init__(self, testStructTable, **kwargs):
super(TestWidget, self).__init__(**kwargs)
Builder.load_file('test.kv')
sm = ScreenManager()
sm.add_widget(MainScreen(name='MainScreen'))
self.add_widget(sm)
# Error accessing the table
print self.testStructTable
# Have the update_test_val continuously called
#Clock.schedule_interval(MainScreen.update_test_val(testStructTable), 1 / 60)
class MainScreen(Screen):
def __init__(self, **kwargs):
testVal = NumericProperty(0)
def update_test_val(self, testStructTable):
# Get testVal from testStructTable
# Something like:
# self.testVal = testStructTable.testVal + 1 ?
self.testVal = self.testVal + 1
test.kv
<MainScreen>:
FloatLayout:
Label:
text: str(root.testVal)
font_size: 80
My aim is to have the testVal constantly updating on the screen by accessing that data structure, however I am currently unable to achieve this, can you please advise?
In your __init__ method you're passing testStructTable and then you're trying to access self.testStructTable which does not exist untill you explicitly make an assignment:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.relativelayout import RelativeLayout
from kivy.properties import NumericProperty
class TestWidget(RelativeLayout):
def __init__(self, testStructTable, **kwargs):
super(TestWidget, self).__init__(**kwargs)
print(testStructTable)
self.testStructTable = testStructTable
print(self.testStructTable)
class TestApp(App):
def build(self):
testStructTable = {'randomVal1': 1, 'testVal': 2, 'randomVal2': 3}
# Issue here parsing the table like this?
return TestWidget(testStructTable)
if __name__ == '__main__':
TestApp().run()
I am trying to learn how to create application in Kivy and I have problem with sending argument to the function. I want to send text from input to the function and print it. Can somebody tell me how can I do it ?
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
class TutorialApp(App):
def gratulation(self, *args):
print args
def build(self):
boxLayout = BoxLayout(spacing=10,orientation='vertical')
g = TextInput(text='Enter gratulation',
multiline=False,
font_size=20,
height=100)
button = Button(text='Send')
button.bind(on_press=self.gratulation)
boxLayout.add_widget(g)
boxLayout.add_widget(button)
return boxLayout
if __name__ == "__main__":
TutorialApp().run()
Yo must get the text from "g" and then send it to the button callback, there is 2 ways of doing this, by a lambda function, or calling your class method aplying to it.
Lambda Version:
from __future__ import print_function ##Need to import this for calling print inside lambda
def build(self):
boxLayout = BoxLayout(spacing=10,orientation='vertical')
g = TextInput(text='Enter gratulation',
multiline=False,
font_size=20,
height=100)
button = Button(text='Send')
buttoncallback = lambda:print(g.text)
button.bind(on_press=buttoncallback)
...
The partial version:
from functools import partial ##import partial, wich allows to apply arguments to functions returning a funtion with that arguments by default.
def build(self):
boxLayout = BoxLayout(spacing=10,orientation='vertical')
g = TextInput(text='Enter gratulation',
multiline=False,
font_size=20,
height=100)
button = Button(text='Send')
buttoncallback = partial(self.gratulation, g.text)
button.bind(on_press=buttoncallback)
...
One way to do it:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
class TutorialApp(App):
def gratulation(self, instance):
print(self.g.text)
def build(self):
boxLayout = BoxLayout(spacing=10,orientation='vertical')
self.g = TextInput(text='Enter gratulation',
multiline=False,
font_size=20,
height=100)
button = Button(text='Send')
button.bind(on_press=self.gratulation)
boxLayout.add_widget(self.g)
boxLayout.add_widget(button)
return boxLayout
if __name__ == "__main__":
TutorialApp().run()
Hope it helps!