Python kivy event processing - python

from kivymd.app import MDApp
from kivy.uix.boxlayout import BoxLayout
from kivymd.uix.boxlayout import MDBoxLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivymd.uix.screen import Screen, MDScreen
from kivymd.uix.fitimage import FitImage
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivymd.uix.card import MDCard
from kivy.uix.image import Image
from kivy.animation import Animation
from kivymd.uix.snackbar import Snackbar
from kivy.clock import Clock
from kivy.uix.label import Label
from kivymd.uix.label import MDLabel
from kivy.core.audio import SoundLoader
from kivy.uix.popup import Popup
from kivy.core.window import Window
from skpy import SkypeEventLoop
from skpy import SkypeEvent
from skpy import SkypeNewMessageEvent
from skpy import SkypeCallMsg
from skpy import Skype
import subprocess
from kivymd.uix.selectioncontrol import MDSwitch
import random
class SkypeRecordApp(MDApp):
def func(self, dt):
class MySkype(SkypeEventLoop):
def onEvent(self, event):
print('Проверка...')
try:
print(event.msg.content)
if event.type == 'NewMessage':
print(event.msg.content)
check_for_call = event.msg.content[:6]
if check_for_call == """{"cp":""":
print("Входящий звонок")
except:
pass
if __name__ == "__main__":
sk = MySkype("email", 'password', autoAck=True)
sk.subscribePresence() # Only if you need contact presence events.
sk.loop()
#problem here
def click(self, switch, value):
if (value):
self.www = Clock.schedule_interval(self.func, 1)
else:
print('off')
self.www.cancel()
def __init__(self, **kwargs):
super().__init__(**kwargs)
Window.clearcolor = (100, 100, 100, 100)
self.window = MDBoxLayout(opacity=0, md_bg_color=[.2, .68, .93, 1], orientation='vertical')
anim = Animation()
anim = Animation(opacity=1)
anim.start(self.window)
def build(self):
self.theme_cls.material_style = "M3"
Window.size = (450, 600)
logo_screen = MDBoxLayout(orientation="vertical")
logo_image = Image(source='skype.png',pos_hint={"center_x":.3, "center_y":.19})
logo_screen.add_widget(logo_image)
logo_screen.add_widget(Label(text="Skyper", font_name="Segoe UI Bold.ttf", font_size=58, pos_hint={"center_x":.3, "center_y":.1}))
self.window.add_widget(logo_screen)
switch = MDSwitch(pos_hint={"center_x":.28, "center_y":.1}, track_color_active="white", on_active=self.click)
self.window.add_widget(switch)
switch.bind(active=self.click)
rec = Label(text="Record", font_size=28, pos_hint={"center_x":.3, "center_y":.1}, size_hint_y=None)
self.window.add_widget(rec)
self.window.add_widget(BoxLayout(orientation="vertical"))
return self.window
SkypeRecordApp().run()
I trying to get events of SkPy with kivymd MDSwitch (when is active), but im already create python kivy loop with
self.www = Clock.schedule_interval(self.func, 1)
problem in because is that loop, Python kivy app stopping when this work, I know about cycles in kivy (can't use in kivy), but how I can do this?
sk.loop()
How I can get events of SkPy in Python kivy?

Related

How can I trace why a variable is not populated at init time in Kivy GUI?

How is it possible that the Kivy GUI app is not load the whole code at the time of initialization?
Is it possible that when we called some function so the execution of the code which is inside that function starts at runtime.
The code is:
from kivymd.app import MDApp
from kivymd.uix.card import MDCard
from kivymd.uix.screen import MDScreen
from kivymd.uix.selectioncontrol import MDCheckbox
from kivymd.uix.textfield import MDTextField
from kivymd.uix.label import MDLabel
from kivymd.uix.boxlayout import MDBoxLayout
from kivy.uix.scrollview import ScrollView
from kivy.metrics import dp
from kivymd.uix.fitimage import FitImage
from kivy.uix.boxlayout import BoxLayout
from kivymd.uix.button import MDRaisedButton
from kivymd.uix.behaviors import RoundedRectangularElevationBehavior
from kivy.uix.screenmanager import Screen,ScreenManager
class my_mdcard(MDCard,RoundedRectangularElevationBehavior):
pass
class Item_Menu(Screen,MDBoxLayout):
list_of_information={"checkbox":[],"labels":[],"quantity":[]}
selected_items= {"checkbox": [], "labels": [], "quantity": []}
def __init__(self,**kwargs):
super(Item_Menu,self).__init__(**kwargs)
self.size_hint=(1,0.9)
self.pos_hint={"top":1}
self.orientation="vertical"
scrollbarwin=ScrollView()
content_box=BoxLayout(orientation='vertical',padding=dp(8),spacing=dp(8),size_hint=(1,None))
content_box.bind(minimum_height=content_box.setter('height'))
for i in range(0,50):
Template_card= my_mdcard(
size_hint_y=None,
size_hint_x=.960,
height = dp(100),
padding = dp(4),
pos_hint={'center_y': .5, 'center_x': .490},
radius = [20,],
elevation = 4,
)
checkbox=MDCheckbox(
size_hint=(None, None),
size= (dp(48),dp(48)),
pos_hint={'center_y': .5}
)
checkbox.bind(active=lambda instance,value:self.Selected_checkbox(instance,value))
self.list_of_information["checkbox"].append(checkbox)
image_box=MDBoxLayout(adaptive_size=True)
image=FitImage(
source="D:/Study/Python/Kivy/images/2.jpg",
size_hint= (None, None),
height=dp(80),
width=dp(130),
radius=[12,],
pos_hint={'center_y':0.5}
)
image_box.add_widget(image)
text_box=MDBoxLayout(orientation="vertical",adaptive_height=True,pos_hint={'center_y':0.5},padding=[12,0,0,0])
item_name=MDLabel(text=f"item{i+1}",font_style="H5",size_hint=(1,None),bold=True,theme_text_color="Primary")
item_name.bind(texture_size=item_name.setter('size'))
self.list_of_information["labels"].append(item_name)
price=MDLabel(text=u"Price: \u20B910/per",font_style="Subtitle1",size_hint=(1,None),bold=True,theme_text_color="Hint")
price.bind(texture_size=price.setter('size'))
quantitybox=MDBoxLayout(orientation='vertical',adaptive_height=True,size_hint_x=0.2,pos_hint = {'center_y': .5,'center_x':0.5})
quantityfield=MDTextField(
hint_text= "Quantity",
mode= "rectangle",
size_hint=(None,None),
width=dp(80),
height= dp(40),
padding=[0,0,15,0]
)
self.list_of_information["quantity"].append(quantityfield)
quantitybox.add_widget(quantityfield)
Template_card.add_widget(checkbox)
Template_card.add_widget(image_box)
Template_card.add_widget(text_box)
text_box.add_widget(item_name)
text_box.add_widget(price)
Template_card.add_widget(quantitybox)
content_box.add_widget(Template_card)
scrollbarwin.add_widget(content_box)
buttonbox=MDBoxLayout(orientation="vertical",pos_hint={"top":0.1},adaptive_height=True)
button=MDRaisedButton(text="Selected!!!",size_hint=(1,0.2))
button.bind(on_release=lambda x:self.Change_window(x))
buttonbox.add_widget(button)
self.add_widget(scrollbarwin)
self.add_widget(buttonbox)
def Selected_checkbox(self,instance,value):
for i in range(0,len(self.list_of_information["checkbox"])):
if instance==self.list_of_information["checkbox"][i] and value== True:
self.selected_items["labels"].append(self.list_of_information["labels"][i])
self.selected_items["quantity"].append(self.list_of_information["quantity"][i])
elif instance==self.list_of_information["checkbox"][i] and value== False :
self.selected_items["labels"].remove(self.list_of_information["labels"][i])
self.selected_items["quantity"].remove(self.list_of_information["quantity"][i])
def Change_window(self,instance):
MyApp.sm.current="Item Description"
class Description_item(Screen):
def __init__(self,**kwargs):
super(Description_item,self).__init__(**kwargs)
print(Item_Menu.selected_items)
wholeContentBoxContainer=MDBoxLayout(orientation="vertical")
for item in range(0,len(Item_Menu.selected_items["labels"])):
label=MDLabel(text=Item_Menu.selected_items["labels"][item].text)
print(Item_Menu.selected_items["labels"][item].text)
quantity=MDLabel(text=Item_Menu.selected_items["quantity"][item].text)
wholeContentBoxContainer.add_widget(label)
wholeContentBoxContainer.add_widget(quantity)
self.add_widget(wholeContentBoxContainer)
class MyApp(MDApp):
sm=ScreenManager()
def build(self):
self.sm.add_widget(Item_Menu(name="Item Menu"))
self.sm.add_widget(Description_item(name="Item Description"))
self.theme_cls.theme_style="Dark"
return self.sm
MyApp().run()
When you run this code so you will see that at the time of initialization of the app the print function is getting print the the dictionary "selected_items" which I never want to be print it out at the time of initialization of the code.
Here is a picture will help you to better understand:
Due to this reason I am unable to access the data of the dictionary "selected_items" in the class "Description_item" because it points to empty list which is the value of the dictionary keys.
So how I can access the data of the dictionary "selected_items"?

python service foreground can't open the app but instead gets stuck in a black screen

Hello guys i have this minimal code where the issue is generated:
from kivy.lang import Builder
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
Builder.load_file('the.kv')
def start_service():
from kivy import platform
if platform == "android":
from android import mActivity
from jnius import autoclass
service = autoclass("org.pck.my_app.ServiceMyservice_5")
mActivity = autoclass("org.kivy.android.PythonActivity").mActivity
service.start(mActivity, "")
print('starting service')
start_service()
class fscreen(Widget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
class theapp(App):
def build(self):
self.screenm = ScreenManager()
self.fscreen = fscreen()
screen = Screen(name = "first screen")
screen.add_widget(self.fscreen)
self.screenm.add_widget(screen)
return self.screenm
theapp().run()
And i have this service.py:
import time
from jnius import autoclass
from plyer import notification
PythonService = autoclass('org.kivy.android.PythonService')
PythonService.mService.setAutoRestartService(True)
cnt = 0
while True:
time.sleep(1)
cnt += 1
print('service has been running for ' + str(cnt))
And a small widget in the.kv file:
<fscreen>
Label:
text: 'Test for Service'
font_size: root.height*0.05
pos: root.width*0.3, root.height*0.5
size: root.width*0.4, root.height*0.1
this a screen after the buildozer deploy:
and this a screen for the foreground from top slide:
and last a black screen:

Problem when trying to make a circular button on kivy

from kivy.uix.button import Button
from kivy.uix.behaviors.button import ButtonBehavior
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import Image
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.clock import Clock
from kivy.uix.widget import Widget
from kivy.graphics import BorderImage
from kivy.graphics import Color, RoundedRectangle, Rectangle, Triangle
from kivy.core.window import Window
#from kivy.config import Config
from kivy.uix.checkbox import CheckBox
from kivy.uix.popup import Popup
from kivy.uix.scrollview import ScrollView
from kivy.uix.filechooser import FileChooserListView
from kivy.properties import ObjectProperty
class OpeningPage(FloatLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.but = RoButton(text = 'START', pos = (350,100), font_size=14, size=(100,60), size_hint=(None,None))
self.add_widget(self.but)
class RoButton(Button):
butt = ObjectProperty()
def __init__(self, **kwargs):
super(RoButton, self).__init__(**kwargs)
text = self.text
with self.canvas:
# Color(1., 0, 0)
self.butt = RoundedRectangle( size= self.size, pos = self.pos, radius =[400])
class UI(App):
def build(self):
self.screen_manager = ScreenManager()
self.opening_page = OpeningPage()
screen = Screen(name ='Opening_Page')
screen.add_widget(self.opening_page)
self.screen_manager.add_widget(screen)
return self.screen_manager
if __name__ == '__main__':
the_app = UI()
the_app.run()
Everytime I try to make a circular button using this code I get a box behind the circle. I tried doing self.canvas.before but still no luck if possible could answers be in python rather than .kv language thanks.
Attached image of problem]1
The box you see is the normal Button image. If you don't want that, probably don't use a Button, instead use class RoButton(ButtonBehavior, Widget):.

Kivy Button on_press function=Popup not calling function

Here's the code that has the problem:
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.core.window import Window
from kivy.properties import StringProperty
from kivy.uix.label import Label
from kivy.app import runTouchApp
from kivy.uix.popup import Popup
import arabic_reshaper
import bidi.algorithm
file = open("/sdcard/ls.txt","r")
li = [i for i in open("/sdcard/code_pinal.txt").read().split('\n\n\n')]
class MessageBox(Popup):
message = StringProperty()
def message_box(self, message):
p = MessageBox()
p.message = message
p.open()
layout = GridLayout(cols=1, spacing=1, size_hint_y=None)
# Make sure the height is such that there is something to scroll.
layout.bind(minimum_height=layout.setter('height'))
for x in li:
ttl = bidi.algorithm.get_display(arabic_reshaper.reshape(x.split(':')[0]))
txt = bidi.algorithm.get_display(arabic_reshaper.reshape(x.split(':')[1]))
btn = Button(text=str(title), font_name='/storage/emulated/0/Download/fonts/DejaVuSans.ttf', size_hint_y=None, height=90, on_press=message_box(text))
layout.add_widget(btn)
root = ScrollView(size_hint=(1, None), size=(Window.width, Window.height))
root.add_widget(layout)
runTouchApp(root)
https://i.stack.imgur.com/u2ePj.jpg
i'm getting errors:
TypeError: message_box() missing 1 required positional argument: 'message'
and
AssertionError: None is not callable
i want to get a popup with the title = "ttl" and text = "txt" varibles when any button pressed for every element on the list "li"
please take it easy with me, i'm Beginner
your trying to get text of button on press
why don't you just get the text from button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.core.window import Window
from kivy.properties import StringProperty
from kivy.uix.label import Label
from kivy.app import runTouchApp
from kivy.uix.popup import Popup
import arabic_reshaper
import bidi.algorithm
file = open("/sdcard/ls.txt","r")
li = [i for i in open("/sdcard/code_pinal.txt").read().split('\n\n\n')]
class MessageBox(Popup):
message = StringProperty()
def message_box(self, btn):
message = btn.text
p = MessageBox()
p.message = message
p.open()
layout = GridLayout(cols=1, spacing=1, size_hint_y=None)
# Make sure the height is such that there is something to scroll.
layout.bind(minimum_height=layout.setter('height'))
for x in li:
ttl = bidi.algorithm.get_display(arabic_reshaper.reshape(x.split(':')[0]))
txt = bidi.algorithm.get_display(arabic_reshaper.reshape(x.split(':')[1]))
btn = Button(text=str(title), font_name='/storage/emulated/0/Download/fonts/DejaVuSans.ttf', size_hint_y=None, height=90, on_press=message_box)
layout.add_widget(btn)
root = ScrollView(size_hint=(1, None), size=(Window.width, Window.height))
root.add_widget(layout)
runTouchApp(root)

Updating multiple Labels with kivy

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()

Categories