Keyerror Display on pyatogui in kivy android app - python

i imported my kivy app to android, but on run it crashes and gives me the above error. I tried moving the location of display 0 but it did not change the error. it tells me the error happens when importing pyautogui.
Code:
import time
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
import pyautogui
import os
class layy(App):
os.environ['DISPLAY'] = ':0'
global t
t = TextInput(hint_text='insert text')
global c
global s
s = TextInput(hint_text='insert time till begin')
c = TextInput(hint_text='insert amount')
def bot(self, instance):
am = c.text
if (am == ""):
am = '0'
l = int(am)
apm = t.text
m = str(apm)
if (m == ""):
m = 'hi'
pm = c.text
if (pm == ""):
pm = '0'
o = int(pm)
base = 0
time.sleep(o)
while (base < l):
pyautogui.typewrite(m)
pyautogui.press('enter')
base = base + 1
def build(self):
b = Button(text='Start Spam')
b.bind(on_press=self.bot)
layout = BoxLayout(orientation='vertical')
sublay1 = BoxLayout(orientation='horizontal')
sublay2 = BoxLayout(orientation='horizontal')
sublay3 = BoxLayout(orientation='horizontal')
layout.add_widget(sublay1)
sublay1.add_widget(t)
layout.add_widget(sublay2)
sublay2.add_widget(s)
sublay2.add_widget(c)
layout.add_widget(sublay3)
sublay3.add_widget(b)
return layout
if __name__ == '__main__':
layy().run()
If anyone knows what to do, please tell me. Sorry if it is simple, i'm new to python.

Related

How to create a gauge using Kivy?

I want to make an internet speed test application for Android with Python.
I have done the back-end side but I have a hard time with the front-end.
After research, I decided to use the Kivy framework, however, I need guidance on how to create a gauge like this.
There are two ways to create a gauge. The first one is by using code with mathematics and the second one is by using graphic files for cadran and needle. Below, you will find the implementation of the second way, with the help of the original code of the gauge widget of Kivy Garden project, in which you will be able to understand how the gauge works more easily.
import kivy
kivy.require('1.6.0')
from kivy.app import App
from kivy.clock import Clock
from kivy.properties import NumericProperty
from kivy.properties import StringProperty
from kivy.properties import BoundedNumericProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.uix.scatter import Scatter
from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.uix.progressbar import ProgressBar
from os.path import join, dirname, abspath
class Gauge(Widget):
'''
Gauge class
'''
unit = NumericProperty(1.8)
value = BoundedNumericProperty(0, min=0, max=100, errorvalue=0)
path = dirname(abspath(__file__))
file_gauge = StringProperty(join(path, "cadran.png"))
file_needle = StringProperty(join(path, "needle.png"))
size_gauge = BoundedNumericProperty(128, min=128, max=256, errorvalue=128)
size_text = NumericProperty(10)
def __init__(self, **kwargs):
super(Gauge, self).__init__(**kwargs)
self._gauge = Scatter(
size=(self.size_gauge, self.size_gauge),
do_rotation=False,
do_scale=False,
do_translation=False
)
_img_gauge = Image(
source=self.file_gauge,
size=(self.size_gauge, self.size_gauge)
)
self._needle = Scatter(
size=(self.size_gauge, self.size_gauge),
do_rotation=False,
do_scale=False,
do_translation=False
)
_img_needle = Image(
source=self.file_needle,
size=(self.size_gauge, self.size_gauge)
)
self._glab = Label(font_size=self.size_text, markup=True)
self._progress = ProgressBar(max=100, height=20, value=self.value)
self._gauge.add_widget(_img_gauge)
self._needle.add_widget(_img_needle)
self.add_widget(self._gauge)
self.add_widget(self._needle)
self.add_widget(self._glab)
self.add_widget(self._progress)
self.bind(pos=self._update)
self.bind(size=self._update)
self.bind(value=self._turn)
def _update(self, *args):
'''
Update gauge and needle positions after sizing or positioning.
'''
self._gauge.pos = self.pos
self._needle.pos = (self.x, self.y)
self._needle.center = self._gauge.center
self._glab.center_x = self._gauge.center_x
self._glab.center_y = self._gauge.center_y + (self.size_gauge / 4)
self._progress.x = self._gauge.x
self._progress.y = self._gauge.y + (self.size_gauge / 4)
self._progress.width = self.size_gauge
def _turn(self, *args):
'''
Turn needle, 1 degree = 1 unit, 0 degree point start on 50 value.
'''
self._needle.center_x = self._gauge.center_x
self._needle.center_y = self._gauge.center_y
self._needle.rotation = (50 * self.unit) - (self.value * self.unit)
self._glab.text = "[b]{0:.0f}[/b]".format(self.value)
self._progress.value = self.value
if __name__ == '__main__':
from kivy.uix.slider import Slider
class GaugeApp(App):
increasing = NumericProperty(1)
begin = NumericProperty(50)
step = NumericProperty(1)
def build(self):
box = BoxLayout(orientation='horizontal', padding=5)
self.gauge = Gauge(value=50, size_gauge=256, size_text=25)
self.slider = Slider(orientation='vertical')
stepper = Slider(min=1, max=25)
stepper.bind(
value=lambda instance, value: setattr(self, 'step', value)
)
box.add_widget(self.gauge)
box.add_widget(stepper)
box.add_widget(self.slider)
Clock.schedule_interval(lambda *t: self.gauge_increment(), 0.03)
return box
def gauge_increment(self):
begin = self.begin
begin += self.step * self.increasing
if 0 < begin < 100:
self.gauge.value = self.slider.value = begin
else:
self.increasing *= -1
self.begin = begin
GaugeApp().run()
Of course, if you don't want to use the default cadran and needle, you will have to design your own, using a vector graphics editor.

Can buildozer made android apps use glob and os modules?

So at the moment in try to figure out why is my small player i wrote in kivy crashes on start. It says build successful and all modules seem to work separately in other tests (except for glob) but this one is pure python as far as i know.
here's my code
import glob
import kivy
from kivy.core.audio import SoundLoader
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.graphics import Rectangle
from kivy.graphics import Color
from kivy.uix.widget import Widget
import random
import os
from android.permissions import request_permissions, Permission
request_permissions([Permission.READ_EXTERNAL_STORAGE])
class PageI(GridLayout):
def __init__(self,**kwargs):
super().__init__( **kwargs)
self.cols = 3
self.state = False
self.music = glob.glob('/Phone/reMusic/*.mp3')#glob.glob('music\\*.mp3')
self.currname = self.music[0]
self.lasttime = 0
self.currsound = SoundLoader.load(self.currname)
fillclr = (round(random.random(),4), round(random.random(),4), round(random.random(),4), 1)
SR = Button(text='forward')
SR.bind(on_press=self.switchoR)
self.add_widget(SR)
placeholder = Label()
self.add_widget(placeholder)
SL = Button(text='backward')
SL.bind(on_press=self.switchoL)
self.add_widget(SL)
placeholder = Label()
self.add_widget(placeholder)
self.PP = Button(on_press = self.switchostate)
self.add_widget(self.PP)
placeholder = Label()
self.add_widget(placeholder)
placeholder = Label()
self.add_widget(placeholder)
self.showcase = Label(text=self.currname)
self.add_widget(self.showcase)
def PPcontrol(self):
if not self.currsound.state == 'play':
self.currsound.play()
self.currsound.seek(self.lasttime)
else:
self.lasttime = int(self.currsound.get_pos())
self.currsound.stop()
def switchostate(self,instance):
self.PPcontrol()
def showsitch(self):
self.showcase.text = self.currname
def switchoR(self,instance):
instance.background_color = (round(random.random(),4), round(random.random(),4), round(random.random(),4), 1)
ind = self.music.index(self.currname)
if ind+1 > len(self.music)-1:
self.currname = self.music[ind - len(self.music) + 1]
else:
self.currname = self.music[ind + 1]
self.lasttime = 0
self.currsound.stop()
self.currsound = SoundLoader.load(self.currname)
self.currsound.play()
self.showsitch()
def switchoL(self,instance):
instance.background_color = (round(random.random(),4), round(random.random(),4), round(random.random(),4), 1)
ind = self.music.index(self.currname)
if ind - 1 < 0:
self.currname = self.music[len(self.music) - 2]
else:
self.currname = self.music[ind - 1]
self.lasttime = 0
self.currsound.stop()
self.currsound = SoundLoader.load(self.currname)
self.currsound.play()
self.showsitch()
class Applet(App):
def build(self):
self.dircheck()
self.p = PageI()
return self.p
def dircheck(self):
try:
if not os.path.exists(os.path.join(os.getcwd(),'\\music')):
os.mkdir(os.path.join(os.getcwd(),'\\music'))
except: None
if __name__ == '__main__':
apper = Applet()
apper.run()
ik its quite messy but as you can see i tried both creating directories and accessing premade one.
and well, im not sure why it dies, i made sure it had all perms in spec file as well.

Trouble Multithreading a Kivy applciation

I'm trying to have the application UI continue to run even while the BLE scan function is running which is asynchronous. I tried creating another thread but, the UI still freezes when I use the activate button. The screen in question is Screen4, the rest is unimportant. I've tried a couple of different methods to get it to work but I'm having trouble implementing some of the example with it either producing an error or just still causing the UI to freeze for a couple of seconds. Here's the code:
import sys
import json
import googlemaps
import pygatt
import time
import asyncio
from bleak import discover
from urllib.request import urlopen
from twilio.rest import Client
from threading import Thread
#UI import libraries
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.properties import StringProperty
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivy.event import EventDispatcher
from kivy.clock import Clock
accSID = '**********'
authtkn = '*********'
twilcli = Client(accSID, authtkn)
sendNum = '********'
key = '*********'
url = 'http://ipinfo.io/json'
i = 0
sm = ScreenManager()
class Screen1(Screen):
def pair_pressed(self):
def BLEdetect (self):
async def run():
devices = await discover()
for d in devices:
print(d)
k = 0
if (str(d).find('DSD TECH') != -1):
global address
address = str(d)[0:18]
print(address)
sm.current = 's2'
k = 1
break
if (k != 1):
k = 0
sm.current = 's3'
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
Clock.schedule_once(BLEdetect, 0.5)
class Screen2(Screen):
def submit_pressed(self):
contact1_inp = ObjectProperty(None)
contact1 = StringProperty('')
self.contact1 = self.contact1_inp.text
phone1_inp = ObjectProperty(None)
phone1 = StringProperty('')
self.phone1 = self.phone1_inp.text
#----------------------------------------------------------------
contact2_inp = ObjectProperty(None)
contact2 = StringProperty('')
self.contact2 = self.contact2_inp.text
phone2_inp = ObjectProperty(None)
phone2 = StringProperty('')
self.phone2 = self.phone2_inp.text
#---------------------------------------------------------------
contact3_inp = ObjectProperty(None)
contact3 = StringProperty('')
self.contact3 = self.contact3_inp.text
phone3_inp = ObjectProperty(None)
phone3 = StringProperty('')
self.phone3 = self.phone3_inp.text
#--------------------------------------------------------------
contact4_inp = ObjectProperty(None)
contact4 = StringProperty('')
self.contact4 = self.contact4_inp.text
phone4_inp = ObjectProperty(None)
phone4 = StringProperty('')
self.phone4 = self.phone4_inp.text
#-------------------------------------------------------------
global contactlst
contactlst = [[self.contact1, self.phone1], [self.contact2, self.phone2],
[self.contact3, self.phone3],[self.contact4, self.phone4]]
#if contaclst is None:
j = 0
while (j < 4):
print("Contact " + str(j + 1) + ": " + contactlst[j][0])
print("Phone " + str(j + 1) + ": " + contactlst[j][1])
j += 1
sm.current = 's4'
class Screen3(Screen):
def tryagain_pressed(self):
sm.current = 's1'
def cancel_pressed(self):
exit()
class Screen4(Screen):
stop = threading.Event()
global BLEscan, i
def BLEscan(self):
while (i == 0):
async def run():
devices = await discover()
for d in devices:
print(d)
k = 0
if (str(d).find(address) != -1):
response = urlopen(url)
data = json.load(response)
city = data['city']
loc = data['loc']
country = data['country']
region = data['region']
gmapurl = 'http://maps.googleapis.com/maps/api/staticmap?center='
gmapurl = gmapurl + loc + '&size=600x600&zoom=14&sensor=true&markers=color:red%7Clabel:A%7C' + loc + '&key=' + key
def waste_time(dt):
pass
while ((k < 4) and (contactlst[k][0] != '')):
mes = 'Please Send Help ' + contactlst[k][0]
info = '{4} \nRegion : {1} \nCountry : {2} \nCity : {3} \nLoc: {0}'.format(loc,region,country,city,mes)
message = twilcli.messages.create(body=info, from_=sendNum, to=contactlst[k][1], media_url= gmapurl)
Clock.schedule_once(waste_time, 3)
k += 1
i = 1
break
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
def second_thread(self):
Clock.schedule_interval(BLEscan, 5)
def activate_pressed (self):
i = 0
threading.Thread(target=self.second_thread).start()
def deactivate_pressed(self):
i = 1
class esosApp(App):
def on_stop(self):
self.root.stop.set()
def build(self):
screenone = Screen1(name='s1')
screentwo = Screen2(name='s2')
screenthree = Screen3(name='s3')
screenfour = Screen4(name='s4')
sm.add_widget(screenone)
sm.add_widget(screentwo)
sm.add_widget(screenthree)
sm.add_widget(screenfour)
return sm
if __name__ == '__main__':
esosApp().run()```

How I can pause a line of code in python without pausing all of the script?

I want to delay a function in the code, but not all the script, because if I do so the countdown animation stops playing because when you use time.sleep() function if puts in sleep all the app. So I ask if there is a way to delay only a function or a line of code that executes the photo function?
This is my code:
import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.videoplayer import Video
from kivy.uix.video import Video
from kivy.config import Config
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
import sys
import os
import subprocess
import datetime
import time
import threading
class MyPhotoBoothApp(App):
def build(self):
global fl
fl = FloatLayout()
fl = FloatLayout(size=(300, 300))
global buttonstart
buttonstart = Button(text=' ', background_color=[0, 0, 0, 0], on_press=self.startcycle)
fl.add_widget(buttonstart)
global videostart
videostart = Video(source='C:/PhotoBooth/animations/Start/TouchHereToStart.mov', state='play', options={'allow_stretch': False})
videostart.options = {'eos': 'loop'}
fl.add_widget(videostart)
return fl
def startcycle(self, *arg):
fl.remove_widget(buttonstart)
fl.remove_widget(videostart)
self.countdown = Video(source='C:/PhotoBooth/animations/Countdown/Countdown.mov', state='play', options={'allow_stretch': False})
self.countdown.options = {'eos': 'false'}
countdowntimer = threading.Thread(target=self.countdown)
fl.add_widget(self.countdown)
#self.takephoto()
return fl
def takephoto(self, *arg):
countdowntimer.join()
print("DONE")
def func_TakeNikonPicture(input_filename):
camera_command = 'C:\Program Files (x86)\digiCamControl\CameraControlCmd.exe'
camera_command_details = '/filename C:testing/' + input_filename + ' /capturenoaf'
full_command=camera_command + ' ' + camera_command_details
p = subprocess.Popen(full_command, stdout=subprocess.PIPE, universal_newlines=True, shell=False)
if(len(sys.argv) < 2):
rawimagename = 'photo.jpg'
else:
files = sys.argv[1:len(sys.argv)]
rawimagename = files[0]
if(os.path.isfile(rawimagename) is True):
print("Image saved")
sys.exit()
current_dt=datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
rawimagename=current_dt + '_' + rawimagename
func_TakeNikonPicture(rawimagename)
#func_TakeNikonPicture(rawimagename)
Config.set('graphics', 'fullscreen', 'auto')
Config.set('graphics', 'window_state', 'maximized')
Config.set('graphics', 'rotation', 0)
MyPhotoBoothApp().run()

Kivy opens two popup windows, when I only expected one

So, I've been trying to get a popup to open on Kivy, and close it with when pressing Escape. However I found myself having to press it twice, and then I found out that it was opening two popups.
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.uix.popup import Popup
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.config import Config
Config.set('kivy', 'exit_on_escape', '0')
class KeyDown(App):
def build(self):
self.popup_exists = 0
Window.bind(on_key_down=self.key_action)
return Widget()
def key_action(self, *args):
key1 = args[1]
key2 = args[2]
special_keys = args[4]
letter = args[3]
if special_keys == ['ctrl'] and letter == 'f': # Ctrl-F
print('Find')
self.open_find_dialog()
if key1 == 13 and key2 == 40 and self.popup_exists == 1: # ENTER KEY
pass
if key1 == 27 and key2 == 41 and self.popup_exists == 1: # ESC
self.find_window.dismiss()
def open_find_dialog(self):
content = BoxLayout(orientation='horizontal')
col1_cont = BoxLayout(size_hint_x = 2,orientation = 'vertical')
col2_cont = BoxLayout(size_hint_x = 4,orientation = 'vertical')
find_labl = Label(text='Find',size_hint_y=None, height = 40)
repl_labl = Label(text='Replace',size_hint_y=None, height = 40)
find_text = TextInput(text='', size_hint_y = None, height = 40)
repl_text = TextInput(text='', size_hint_y = None, height = 40)
col1_cont.add_widget(find_labl)
col1_cont.add_widget(repl_labl)
col2_cont.add_widget(find_text)
col2_cont.add_widget(repl_text)
content.add_widget(col1_cont)
content.add_widget(col2_cont)
self.find_window = Popup(title='Find and Replace',content = content,size_hint=(None, None), size=(240, 140))
self.find_window.open()
self.popup_exists = 1
if __name__ == '__main__':
KeyDown().run()
Does anyone know why would it open two popups? How would I prevent it from doing so?

Categories

Resources