def add_var(self, var_name, eqn_text, do_save=True): """Add to the variables bubble list and dictionary. Arguments: - `self`: - `var_name`: - `eqn_text`: """ # This function was actually created and modeled after # self.add_to_history. Relevant comments can be found there. var_exists = var_name in self.var_dict self.var_dict[var_name] = eqn_text if do_save: with open(VARDB_FILE, "wb") as var_file: pickle.dump(self.var_dict, var_file) if not var_exists: new_btn = BubbleButton(text=var_name) last_pos = len(self.var_dict) new_btn.bind(on_press=lambda *args: self.set_eqn(self.var_dict[var_name], len(self.history_stack) + 1)) try: kivy.require("1.4.2") self.var_list_bubble.content.add_widget(new_btn, last_pos + 1) except Exception: self.var_list_bubble.content.clear_widgets() self.var_list_bubble.content.add_widget(new_btn) for dice_roll in reversed(self.var_list_stack): dice_bubble = BubbleButton(text=dice_roll) dice_bubble.bind(on_press=self.var_dict[dice_roll]) self.var_list_bubble.content.add_widget(dice_bubble) self.var_list_stack.append(var_name) if not hasattr(self, "bubble_height_var"): self.bubble_height_var = self.dice_eqn_input.height else: self.var_list_bubble.height += self.bubble_height_var self.var_list_bubble.parent.height += self.bubble_height_var
def setUp(self): """ The set up for each test constructs a new app """ import kivy kivy.require('1.8.0') from kivy.config import Config from kivy.interactive import InteractiveLauncher from kivy.base import EventLoop from kivy.core.window import Window Config.set('modules', 'recorder', '') from main import AnonTunnelApp self.ata = AnonTunnelApp()
def execute_directives(self): for ln, cmd in self.directives: cmd = cmd.strip() if __debug__: trace('Parser: got directive <%s>' % cmd) if cmd[:5] == 'kivy ': version = cmd[5:].strip() if len(version.split('.')) == 2: version += '.0' require(version) elif cmd[:4] == 'set ': try: name, value = cmd[4:].strip().split(' ', 1) except: Logger.exception('') raise ParserException(self, ln, 'Invalid directive syntax') try: value = eval(value) except: Logger.exception('') raise ParserException(self, ln, 'Invalid value') global_idmap[name] = value elif cmd[:7] == 'import ': package = cmd[7:].strip() l = package.split(' ') if len(l) != 2: raise ParserException(self, ln, 'Invalid import syntax') alias, package = l try: if package not in sys.modules: try: mod = __import__(package) except ImportError: mod = __import__('.'.join(package.split('.')[:-1])) # resolve the whole thing for part in package.split('.')[1:]: mod = getattr(mod, part) else: mod = sys.modules[package] global_idmap[alias] = mod except ImportError: Logger.exception('') raise ParserException(self, ln, 'Unable to import package %r' % package) else: raise ParserException(self, ln, 'Unknown directive')
def parse_version(self, line): """Parse the version line. The version line is always the first line, unindented and has the format: #:kivy <version> """ ln, content = line if not content.startswith("#:kivy "): raise ParserError(self, ln, "Invalid doctype, must start with " "#:kivy <version>") version = content[6:].strip() if len(version.split(".")) == 2: version += ".0" require(version) if __debug__: trace("Parser: Kivy version is %s" % version)
def execute_directives(self): for ln, cmd in self.directives: cmd = cmd.strip() if __debug__: trace("Parser: got directive <%s>" % cmd) if cmd[:5] == "kivy ": version = cmd[5:].strip() if len(version.split(".")) == 2: version += ".0" require(version) elif cmd[:4] == "set ": try: name, value = cmd[4:].strip().split(" ", 1) except: Logger.exception("") raise ParserException(self, ln, "Invalid directive syntax") try: value = eval(value) except: Logger.exception("") raise ParserException(self, ln, "Invalid value") global_idmap[name] = value elif cmd[:7] == "import ": package = cmd[7:].strip() l = package.split(" ") if len(l) != 2: raise ParserException(self, ln, "Invalid import syntax") alias, package = l try: if package not in sys.modules: try: mod = __import__(package) except ImportError: mod = __import__(".".join(package.split(".")[:-1])) # resolve the whole thing for part in package.split(".")[1:]: mod = getattr(mod, part) else: mod = sys.modules[package] global_idmap[alias] = mod except ImportError: Logger.exception("") raise ParserException(self, ln, "Unable to import package %r" % package) else: raise ParserException(self, ln, "Unknown directive")
def add_to_history(self, eqn_text, do_save=True): """Add to equations history Arguments: """ # new button to be added to the history list new_btn = BubbleButton(text=eqn_text) last_pos = len(self.history_stack) eqn_fn = lambda *args: self.set_eqn(eqn_text, last_pos) if do_save: append_overwrite = "a" if last_pos < 40 else "w" with open(DICE_HISTORY_FILE, append_overwrite) as dh_file: # We only care about the last 40 if last_pos >= 40: for eqn in self.history_stack[last_pos - 40 : last_pos]: dh_file.write(eqn + "\n") dh_file.write(eqn_text + "\n") new_btn.bind(on_press=eqn_fn) try: # kivy 1.4.2 will respect the order bubble buttons are # added kivy.require("1.4.2") # this will throw an exception if # it's not 1.4.2 or later self.history_stack.append(eqn_fn) self.dice_history.content.add_widget(new_btn, last_pos + 1) except Exception: # nasty ugly work around for kivy issue #819 self.dice_history.content.clear_widgets() self.dice_history.content.add_widget(new_btn) for dice_roll in reversed(self.history_stack): dice_bubble = BubbleButton(text=dice_roll()) dice_bubble.bind(on_press=dice_roll) self.dice_history.content.add_widget(dice_bubble) self.history_stack.append(eqn_fn) self.dice_eqn_input.history_stack_pos = last_pos + 1 if not hasattr(self, "bubble_height"): self.bubble_height = self.dice_eqn_input.height else: self.dice_history.height += self.bubble_height # Why change the following? Because the parent is actually # an anchor layout. self.dice_history.parent.height += self.bubble_height
import kivy kivy.require('1.4.2') import os import sys from kivy.app import App from kivy.factory import Factory from kivy.lang import Builder, Parser, ParserException from kivy.properties import ObjectProperty from kivy.config import Config from kivy.compat import PY2 from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.boxlayout import BoxLayout from kivy.uix.codeinput import CodeInput from kivy.animation import Animation from kivy.clock import Clock from login.login import Login from dashboard.dashboard import Dashboard class Csdent(BoxLayout): '''Csdent of widgets. This is the root widget of the app. It contains a tabbed pain of widgets that can be displayed and a textbox where .kv language files for widgets being demoed can be edited. The entire interface for the Csdent is defined in kivycatalog.kv, although individual containers are defined in the container_kvs directory. To add a container to the catalog, first create the .kv file in container_kvs The name of the file (sans .kv) will be the name of the widget available inside the kivycatalog.kv
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import kivy kivy.require('1.6.0') import kivy.utils as utils from kivy.support import install_twisted_reactor from kivy.support import install_android install_twisted_reactor() install_android() PLATFORM = utils.platform() if PLATFORM == "android": import android android.init() from twisted.internet import reactor, protocol from kivy.clock import Clock from re import findall from random import randint from kivy.uix.label import Label from kivy.uix.floatlayout import FloatLayout
import kivy kivy.require("1.9.0") from kivy.app import App from base.dictionary import Dictionary from kivy.core.window import Window from typing import Undefined from chinese.search import Search from chinese.review import Review class Chinese(App): # Needed for searching the db from /base search = Undefined(Search) review = Undefined(Review) def build(self): self.search = Search() self.review = Review() # Set the background color for the app Window.clearcolor = (0.9, 0.9, 0.9, 1) return Dictionary(app=self, font="file/font/chinese_1.ttc", font_awesome="file/font/font_awesome.ttf") if __name__ == '__main__':
#!/usr/bin/python # -*- coding: utf-8 -*- import kivy kivy.require('1.8.0') from kivy.app import App from kivy.uix.widget import Widget from GameScreens.QGScreen import QGScreen from Manager.GameManager import GameManager from Model.Structure import Structure from Model.Leader import Leader from Model.User import User from Model.Card import Card from Model.Game import Game class TestWidget(Widget): def __init__(self, **kwargs): super(type(self), self).__init__(**kwargs) structure = Structure(id=0, level=2) structure.pos["left"] = 34.94 structure.pos["right"] = 62.29 structure.pos["top"] = 42.04 structure.pos["bottom"] = 60.46 structure1 = Structure(id=1, level=1)
import random from math import cos, sin, pi, sqrt, asin import kivy from kivy.app import App from kivy.uix.widget import Widget from kivy.graphics import Rectangle, Color, Line from kivy.clock import Clock kivy.require("1.9.1") class CanvasWidget(Widget): def __init__(self, **kwargs): self.x1, self.y1 = 500, 200 self.fi = 0 super(CanvasWidget, self).__init__(**kwargs) with self.canvas: Color(0, 1, 1, 1) self.rect = Rectangle(pos=(self.x1, self.y1), size=(6, 6)) self.bind(pos=self.update_rect1, size=self.update_rect1) self.radius = 300 Color(0, 1, 0, 1) self.line = Line(points=[400, 300, 700, 300], width=2)
# Kivy.org must be installed to use this. Due to monitor driver compatibility reasons windows computers worked best for my testing. Testing was completed with a Planar Helium PCT2785 27" monitor. # Everytime the touchscreen is pressed draw a random colored square and send the x & y percentages to the web server. import kivy import urllib.request kivy.require("1.1.1") from kivy.app import App from kivy.uix.widget import Widget from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty from kivy.vector import Vector from kivy.clock import Clock from kivy.core.window import Window import json from kivy.graphics import * from kivy.config import Config from random import randint import datetime as dt class RawCord(Widget): already_published = [] def was_point_already_published(self, x, y): tmp_set = [x, y] if tmp_set in self.already_published: return True else: if self.was_similar_point_already_published(x, y):
#!/usr/bin/env python import kivy kivy.require("1.0.7") from os.path import dirname, isdir, join, exists from kivy.animation import Animation from kivy.app import App from kivy.clock import Clock from kivy.core.window import Window from kivy.factory import Factory from kivy.graphics.fbo import Fbo from kivy.graphics import RenderContext from kivy.lang import Builder from kivy.properties import StringProperty, ObjectProperty, NumericProperty, BooleanProperty from kivy.resources import resource_add_path from kivy.uix.floatlayout import FloatLayout Builder.load_string( """ <SlideShaderContainer>: canvas: Rectangle: pos: self.pos size: self.size texture: self.fbo_texture <Slides>: container1: container1 container2: container2 containerb: containerb
This is a Triangle widget with a triangle shape based on 3 points (p1, p2, p3), plus a custom collision function. The p1, p2, p3 are automatically calculated from the position and the size of the Widget bounding box. We are using them to draw the triangle shape. (Please note in the kv the special case for Scatter.) Then we need to setup a new collision function to collide only on the triangle. We are using a external method that will check if a point is inside a polygon (we consider our triangle as a polygon). ''' import kivy kivy.require('1.0.8') from kivy.uix.scatter import Scatter from kivy.properties import ListProperty from kivy.lang import Builder Builder.load_string(''' <Triangle>: # example for doing a triangle # this will automatically recalculate pX from pos/size p1: 0, 0 p2: self.width, 0 p3: self.width / 2, self.height # If you use a Widget instead of Scatter as base class, you need that: #p1: self.pos
import kivy kivy.require('1.10.1') from kivy.lang import Builder from kivy.uix.recycleview.views import RecycleDataViewBehavior from kivy.uix.boxlayout import BoxLayout from kivy.properties import StringProperty, BooleanProperty Builder.load_file('app/widgets/device_input/display.kv') class DeviceInput(RecycleDataViewBehavior, BoxLayout): index = None device_id = StringProperty() device_name = StringProperty() device_active = BooleanProperty() device_action = StringProperty() def refresh_view_attrs(self, rv, index, data): self.index = index return super(DeviceInput, self).refresh_view_attrs(rv, index, data)
import kivy kivy.require("1.10.0") import json import os import sys import datetime from kivy.core.image import Image as kivyImage from kivy.uix.screenmanager import ScreenManager, Screen from kivy.properties import StringProperty, ObjectProperty from kivy.clock import Clock import common_modules from script.get_parameters_reforms_tests_variables_folder_paths import * from script.interpeters.variables_file_interpeter import * from script.interpeters.parameters_interpeter import * from script.interpeters.reforms_file_interpeter import * from script.download_openfisca_system import download_and_install as download_and_install_openfisca from script.download_openfisca_system import check_package_is_installed from script.download_openfisca_system import install_country_package from script.Simulation.Situation_for_simulation import * from script.reforms_maker.reform_variables import * from folder_screen_widgets.personalized_widget import * class InitScreen(Screen): """ Initial screen """ download_information = StringProperty( "[color=000000][b][size=20]If you want to download an openfisca-system\nplease click ones of the following buttons[/size][b][/color]" )
import kivy kivy.require("1.2.0") from kivy.app import App from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout #this line we will use later to make a link to another kv ''' class Mainwin(BoxLayout): def __init__(self,**kwargs): super().__init__( **kwargs) ''' class Mainapp(App): def build(self): return Label(text="Hello kamel altohamy") if __name__ == "__main__": Mainapp().run()
from kivy.app import App import kivy """ Enkel "halla verden" app. """ kivy.require("1.8.0") #versjonskontroll. Trenger minimum kivy v "x.y.z" from kivy.uix.label import Label # En Label kan også fungere som en knapp eller lignende class SimpleKivy(App): def build(self): return Label(text="halla verden") if __name__ == "__main__": SimpleKivy().run()
''' author : monsef alahem (based on Dr.ally abbara algorithms) email : [email protected] version : 1.0 start : 09-08-2019 ''' import math import kivy kivy.require("1.11.1") #necesary for utf # import sys # reload(sys) # sys.setdefaultencoding('utf-8') from kivy.app import App from kivy.clock import Clock from kivy.compat import string_types from kivy.core.window import Window from kivy.graphics import Color, Rectangle from kivy.lang import Builder from kivy.metrics import sp, dp from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout from kivy.uix.scrollview import ScrollView from kivy.uix.label import Label #import android, time
import kivy kivy.require('1.11.0') from kivy.config import Config Config.read("config.ini") from kivy.app import App from kivy.clock import Clock from frame import PhotoFrame from frame.Downloader import fetch_files from frame.WiFi import WiFiSettings class PhotoFrameApp(App): def build(self): photo = PhotoFrame() photo.refresh_images(None) Clock.schedule_interval(photo.step_forward, 60.0) Clock.schedule_interval(fetch_files, 60.0*60.0*24) return photo if __name__ == '__main__': # fetch_files() PhotoFrameApp().run()
#!/usr/bin/python if __name__ == '__main__': import kivy kivy.require('1.9.2') from kivy.base import runTouchApp from kivy.lang import Builder from kivy.properties import NumericProperty, BooleanProperty from kivy.uix.boxlayout import BoxLayout from kivy.uix.recycleview import RecycleView from kivy.uix.recycleview.layout import RecycleLayoutManagerBehavior from rockberry_player.widgets.dialbehavior import DialSlider from rockberry_player.widgets.dialrecycleview import DialRecycleView class TestWidget(BoxLayout): pass class TestRecycleView(DialRecycleView): pass class TestItem(BoxLayout): number = NumericProperty(0) Builder.load_string(""" <TestItem>: Label:
import kivy kivy.require('2.0.0rc') from kivy.app import App from kivy.uix.screenmanager import Screen, ScreenManager from kivy.lang.builder import Builder from kivy.properties import ObjectProperty from database import add_user, close, login from kivy.uix.floatlayout import FloatLayout from kivy.uix.popup import Popup from kivy.uix.button import Button from kivy.uix.label import Label class Login(Screen): user = ObjectProperty(None) pw = ObjectProperty(None) def login(self): i = login([self.user.text, self.pw.text]) if len(i) > 1: muncul(i) SM.current = i[0] class Create(Screen): user = ObjectProperty(None) pw = ObjectProperty(None) email = ObjectProperty(None) def create(self, x):
# -*- coding: utf-8 -*- import kivy kivy.require('1.1.3') import os import pickle import gc from kivy.factory import Factory from kivy.properties import ObjectProperty, StringProperty from kivy.uix.screenmanager import ScreenManager, Screen from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.stacklayout import StackLayout from kivy.uix.widget import Widget from kivy.uix.carousel import Carousel from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.textinput import TextInput from kivy.uix.scatter import Scatter from kivy.uix.togglebutton import ToggleButton from kivy.uix.spinner import Spinner from kivy.uix.dropdown import DropDown from kivy.uix.popup import Popup from kivy.uix.scrollview import ScrollView
import kivy kivy.require('1.0.9') from kivy.lang import Builder from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.popup import Popup from kivy.properties import * from kivy.uix.progressbar import ProgressBar from kivy.clock import Clock from jnius import autoclass, cast import urllib import json import re import os import threading import re import datetime import main_utils __all__ = ["check_update"] Builder.load_string(''' <ConfirmPopup>: cols:1 Label: text: root.text size_hint_y: 16 GridLayout:
The file pictures.kv describes the interface and the file shadow32.png is the border to make the images look like framed photographs. Finally, the file android.txt is used to package the application for use with the Kivy Launcher Android application. For Android devices, you can copy/paste this directory into /sdcard/kivy/pictures on your Android device. The images in the image directory are from the Internet Archive, `https://archive.org/details/PublicDomainImages`, and are in the public domain. ''' import kivy kivy.require('1.0.6') import urllib from kivy.uix.image import AsyncImage from glob import glob from random import randint from os.path import join, dirname from kivy.app import App from kivy.logger import Logger from kivy.uix.scatter import Scatter from kivy.properties import StringProperty # FIXME this shouldn't be necessary from kivy.core.window import Window class Picture(Scatter):
You can also run this with a 'r' parameter to pick a random method. There are lots of logging options to make this easier to debug: the execution order may not be obvious. Each time you run the command, only one kivy application is created. This uses the file testkvfile.kv and the file app_suite_data/testkvdir.kv. ''' from __future__ import print_function import sys import re from random import choice import kivy kivy.require('1.8.0') # 1.8 is when kv_directory became part of app. from kivy.app import App from kivy.uix.button import Button from kivy.lang import Builder from kivy.uix.floatlayout import FloatLayout # Note that importing FloatLayout causes Kivy to execute, including # starting up the Logger and some other messages. print("** In main program, done with imports") class TestBuildApp(App): """ Use build() function to return a widget. """ def build(self): """ Build called by kivy when an App is started. Called after trying to load a .kv file.
#To exit: esc then ctrl-c seems to work import kivy kivy.require('1.1.1') from kivy.app import App from kivy.uix.widget import Widget from kivy.properties import NumericProperty, ReferenceListProperty,\ ObjectProperty from kivy.vector import Vector from kivy.clock import Clock from kivy.core.window import Window import json class RawCord(Widget): def on_touch_down(self, touch): data = [str(float(touch.x) / float(Window.size[0])),str(float(touch.y) / float(Window.size[1]))] with open('kivy_touch_down_log.json', 'w') as outfile: json.dump(data, outfile) def on_touch_up(self, touch): return False #print "UP" #print "X: " + str(float(touch.x) / float(Window.size[0])) #print "Y: " + str(float(touch.y) / float(Window.size[1])) class RawCordApp(App): def build(self): g = RawCord() return g
from kivy.core.window import Window from kivymd.uix.dialog import MDDialog from kivymd.uix.button import MDFlatButton, MDRaisedButton from kivymd.app import MDApp from kivymd.uix.label import MDLabel from kivymd.toast import toast import pymysql # No imports after this line! # System configs Config.set("graphics", "resizable", "false") Config.set("graphics", "width", 450) Config.set("graphics", "height", 800) kivy.require("2.0.0") Window.size = (450, 800) # No system settings and configs after this line! # Functions def generateModalTextBook(book): """Создание текста модальных окон книг.""" owner = book[0] id = book[2] isbn = book[3] author = book[5] description = book[6] tags = showTags(book[7]) station = book[8]
#!/bin/env python ### ### ### Author = 'Adam Grigolato' Version = '0' ### ### ### import kivy kivy.require('1.7.2') from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.label import Label from kivy.uix.button import Button from kivy.core.window import Window from kivy.uix.boxlayout import BoxLayout from kivy.uix.floatlayout import FloatLayout from kivy.properties import NumericProperty from kivy.uix.image import Image from kivy.clock import Clock from kivy.graphics import Rectangle from functools import partial from random import randint from kivy.config import Config Config.set('graphics','resizable',0) # don't make the app re-sizeable # Graphics fix # this fixes drawing issues on some phones
import kivy kivy.require('1.8.0') from kivy.uix.screenmanager import * from kivy.uix.modalview import ModalView from kivy.uix.relativelayout import RelativeLayout from kivy.clock import Clock from kivy.uix.button import Button from kivy.uix.image import Image from kivy.uix.scrollview import ScrollView from kivy.uix.stencilview import StencilView from kivy.uix.boxlayout import BoxLayout from kivy.uix.scatter import Scatter from kivy.uix.label import Label from kivy.animation import * from kivy.graphics import * from functools import partial import random from random import shuffle from math import sqrt import g import utils as u import ocanim as oa import pieces class mainScreen(Screen): """As the name suggests, this is the title screen.""" def __init__(self, name, **kwargs):
""" This library provides functions to import and initialize cefpython found in PYTHONPATH. """ import atexit import os import signal import sys import tempfile import kivy from kivy.app import App from kivy.clock import Clock from kivy.logger import Logger kivy.require("1.8.0") # Try import from package (PYTHONPATH) try: from cefpython3 import cefpython Logger.info("CEFLoader: cefpython3 imported from package") except ImportError: Logger.critical("CEFLoader: Failed to import cefpython") raise Exception("Failed to import cefpython") cefpython_loop_event = None def cefpython_initialize(cef_browser_cls): global cefpython_loop_event if cefpython_loop_event:
# File name: layouts.py import kivy from kivy.uix.slider import Slider kivy.require('1.7.0') class SpeedSlider(Slider): def __init__(self, **kwargs): super(SpeedSlider, self).__init__(**kwargs) self.min = 1 self.max = 200 self.value = 50 self.touches_on = 0 def on_touch_down(self, touch): if self.disabled or not self.collide_point(*touch.pos): return if touch.is_mouse_scrolling: if 'down' in touch.button or 'left' in touch.button: if self.step: self.value = min(self.max, self.value + self.step) else: self.value = min( self.max, self.value + (self.max - self.min) / 20) if 'up' in touch.button or 'right' in touch.button: if self.step: self.value = max(self.min, self.value - self.step) else: self.value = max(
import kivy import urllib2 import json import pprint import functools kivy.require('1.7.1') from kivy.app import App from kivy.lang import Builder from kivy.properties import ListProperty from kivy.uix.widget import Widget from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.togglebutton import ToggleButton from kivy.uix.gridlayout import GridLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.listview import ListView from functools import partial from kivy.core.window import Window from kivy.uix.scrollview import ScrollView from kivy.uix.modalview import ModalView from kivy.uix.textinput import TextInput Builder.load_string(''' # define how clabel looks and behaves <CLabel>: canvas.before: Color: rgb: self.bgcolor Rectangle: size: self.size
#http://stackoverflow.com/questions/31458331/running-multiple-kivy-apps-at-same-time-that-communicate-with-each-other?noredirect=1&lq=1 #https://github.com/kivy/kivy/wiki/Snippets #https://github.com/kivy/kivy/wiki/User-Snippets #http://stackoverflow.com/a/38057351 #interface usability variables (timing, colors, etc) #big/display text: Chewy (color: ff531c; ) #normal interface text: Roboto Regular (color: HTML; ) #http://cheparev.com/kivy-connecting-font/ #color for currently-satisfied conditions: 5cb85c #else (background, etc): white #the stuff begins #MAKE IT TABBED! (L->R: Do, Add, Conditions) kivy.require('1.9.2') from kivy.app import App from kivy.uix.label import Label class Marceline(App): def build(self): return Label(text='Hello world') if __name__ == '__main__': Marceline().run()
import kivy kivy.require('1.0.5') from kivy.uix.floatlayout import FloatLayout from kivy.app import App from kivy.properties import ObjectProperty, StringProperty class Controller(FloatLayout): '''Create a controller that receives a custom widget from the kv lang file. Add an action to be called from the kv lang file. ''' text2 = 'f**k' label_wid = ObjectProperty() info = StringProperty() def do_action(self): self.label_wid.text = self.text2#'My label after button press' self.info = 'New info text' def prr(self, data): print(data) return '12' class LearnApp(App): def build(self): return Controller(info='Hello world')
import kivy kivy.require('1.0.6') from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.uix.label import Label from kivy.graphics import Color, Rectangle, Point, GraphicException from random import random from math import sqrt def calculate_points(x1, y1, x2, y2, steps=5): dx = x2 - x1 dy = y2 - y1 dist = sqrt(dx * dx + dy * dy) if dist < steps: return None o = [] m = dist / steps for i in xrange(1, int(m)): mi = i / m lastx = x1 + dx * mi lasty = y1 + dy * mi o.extend([lastx, lasty]) return o class Touchtracer(FloatLayout): def on_touch_down(self, touch): win = self.get_parent_window()
# -*- coding: utf-8 -*- ''' Generic map viewer widget for kivy. sourced from mtMaps for pyMT by tito (Mathieu Virbel / kivy dev team) ported to kivy by relet (Thomas Hirsch / Statens kartverk) ''' import kivy kivy.require('1.0.7') from kivy.factory import Factory from kivy.cache import Cache from kivy.logger import Logger from kivy.loader import Loader from kivy.clock import Clock from kivy.uix.widget import Widget from kivy.uix.scatter import ScatterPlane from kivy.uix.stencilview import StencilView from kivy.uix.button import Button from kivy.uix.image import Image from kivy.uix.popup import Popup from kivy.uix.label import Label from kivy.graphics import Color, Rectangle, Ellipse, Line from kivy.graphics.transformation import Matrix from kivy.vector import Vector import time, pickle
from kivy.uix.textinput import TextInput # to use buttons: from kivy.uix.button import Button #from kivy.uix.screenmanager import ScreenManager, Screen import socket_client from kivy.clock import Clock import os import sys from kivy.uix.screenmanager import * from kivy.core.window import Window from kivy.uix.scrollview import ScrollView from kivy.uix.scrollview import ScrollView kivy.require("1.10.1") class ConnectPage(GridLayout): # runs on initialization def __init__(self, **kwargs): super().__init__(**kwargs) self.cols = 2 # used for our grid if os.path.isfile("prev_detail.txt"): with open("prev_details.txt","r") as f: d = f.read().split(",") prev_ip = d[0]
#!/usr/bin/python """ @author Spencer Bliven <*****@*****.**> """ import sys import os import optparse import numpy as np import cv2 import matplotlib.pyplot as plt import kivy kivy.require('1.4.0') from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.boxlayout import BoxLayout from kivy.properties import NumericProperty, ReferenceListProperty,\ ObjectProperty, AliasProperty from kivy.vector import Vector from kivy.clock import Clock from kivy.graphics import Color,Rectangle,Line def texture2img(texture): """Extracts the pixels from a texture and put them into a numpy BGRA image""" img = np.fromstring(texture.pixels,np.uint8).reshape([texture.height,texture.width,4]) return img def img2texture(img,texture):
import kivy, sys, base64, json from termcolor import colored sys.path.append('../') kivy.require('1.10.0') # replace with your current kivy version ! from GUI.connection import Connection import threading from kivy.app import App from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.stacklayout import StackLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.scrollview import ScrollView from kivy.uix.slider import Slider from kivy.uix.image import Image from functools import partial from kivy.core.window import Window from termcolor import colored import netifaces as ni from sys import platform import qrcode #from PIL import Image as img if platform == "linux" or platform == "linux2": # linux interf = 'wlp5s0' elif platform == "darwin": # OS X interf = 'en0' ip = ni.ifaddresses(interf)[ni.AF_INET][0]['addr']
inspector.create_inspector(Window, button) return button Demo().run() To remove the Inspector, you can do the following:: inspector.stop(Window, button) """ __all__ = ("start", "stop", "create_inspector") import kivy kivy.require("1.0.9") import weakref from kivy.animation import Animation from kivy.logger import Logger from kivy.uix.widget import Widget from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.togglebutton import ToggleButton from kivy.uix.textinput import TextInput from kivy.uix.image import Image from kivy.uix.treeview import TreeViewNode from kivy.uix.gridlayout import GridLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.modalview import ModalView
import kivy kivy.require('1.10.0') from kivy.app import App from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager, Screen Builder.load_string(""" <ScreenOne>: BoxLayout: Button: text: "Go to Screen 2" on_press: root.manager.transition.direction = "left" root.manager.transition.duration = 1 root.manager.current = "screen_two" <ScreenTwo>: BoxLayout: Button: text: "Got to Screen 1" on_press: root.manager.transition.direction = "left" root.manager.transition.duration = 1 root.manager.current = "screen_one" """) class ScreenOne(Screen): pass
import kivy kivy.require("1.8.0") from random import randint import sys from kivy.properties import NumericProperty, ReferenceListProperty, BooleanProperty, ObjectProperty, ListProperty from kivy.uix.image import Image from kivy.vector import Vector from kivy.app import App from kivy.clock import Clock from kivy.uix.widget import Widget class Background(Widget): image_one = ObjectProperty(Image()) image_two = ObjectProperty(Image()) velocity_x = NumericProperty(0) velocity_y = NumericProperty(0) velocity = ReferenceListProperty(velocity_x, velocity_y) def update(self): self.image_one.pos = Vector(*self.velocity) + self.image_one.pos self.image_two.pos = Vector(*self.velocity) + self.image_two.pos if self.image_one.right <= 0: self.image_one.pos = (self.width, 0) if self.image_two.right <= 0: self.image_two.pos = (self.width, 0) def update_position(self):
''' Widget animation ================ This example demonstrates creating and applying a multi-part animation to a button widget. You should see a button labelled 'plop' that will move with an animation when clicked. ''' import kivy kivy.require('1.0.7') from kivy.animation import Animation from kivy.app import App from kivy.uix.widget import Widget from kivy.clock import Clock import Leap import fluidsynth from record import record_process_signal, record_signal import time import soundfile as sf import sounddevice as sd from kivy.graphics import Rectangle, Color from midi_player import run_midi_player from kivy.uix.label import Label from kivy.core.window import Window BLOCK_COLOR = (244/255, 175/255, 27/255, 1) #(244/255, 159/255, 28/255, 1) #(1, 1, 0, 1)
Available inspect interactions: * tap once on a widget to select it without leaving inspect mode * double tap on a widget to select and leave inspect mode (then you can manipulate the widget again) Some properties can be edited in live. However, this due to delayed usage of some properties, you might have crash if you didn't handle all the case. ''' __all__ = ('start', 'stop') import kivy kivy.require('1.0.9') import weakref from kivy.animation import Animation from kivy.logger import Logger from kivy.uix.widget import Widget from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.togglebutton import ToggleButton from kivy.uix.textinput import TextInput from kivy.uix.image import Image from kivy.uix.treeview import TreeViewNode from kivy.uix.gridlayout import GridLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.boxlayout import BoxLayout from kivy.graphics import Color, Rectangle, PushMatrix, PopMatrix, \
# This is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # # See the GNU General Public License for more details. You should # have received a copy of the GNU General Public License along with # this code. If not, see <http://www.gnu.org/licenses/>. import time import kivy kivy.require('1.10.0') from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.accordion import Accordion, AccordionItem from kivy.logger import Logger from autosportlabs.widgets.scrollcontainer import ScrollContainer from kivy.metrics import dp, sp from utils import * class BaseChannelView(BoxLayout): channelConfig = None channels = None def __init__(self, **kwargs): super(BaseChannelView, self).__init__(**kwargs) self.ids.sr.bind(on_sample_rate = self.on_sample_rate)
""" # Author: Zen-CODE from kivy.app import App from kivy.lang import Builder from kivy.core.window import Window from kivy.uix.vkeyboard import VKeyboard from kivy.properties import ObjectProperty from kivy.uix.button import Button from functools import partial from kivy.config import Config from kivy.uix.screenmanager import Screen, ScreenManager from kivy import require # This example uses features introduced in Kivy 1.8.0, namely being able # to load custom json files from the app folder. require("1.8.0") Builder.load_string(''' <KeyboardScreen>: displayLabel: displayLabel kbContainer: kbContainer BoxLayout: orientation: 'vertical' Label: size_hint_y: 0.15 text: "Available Keyboard Layouts" BoxLayout: id: kbContainer size_hint_y: 0.2 orientation: "horizontal" padding: 10
import kivy kivy.require('1.9.0') # replace with your current kivy version ! from kivy.config import Config par_width = 470 par_height = 800 Config.set('graphics', 'width', '470') Config.set('graphics', 'height', '800') from kivy.core.window import Window from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout from kivy.uix.label import Label from kivy.uix.textinput import TextInput from main_manager import MainManager from widgets.create_family import CreateFamily from kivy.app import App from kivy.uix.widget import Widget from viewport import Viewport main_manager = MainManager() class MainWidget(FloatLayout):
#This program is free software; you can redistribute it and/or #modify it under the terms of the GNU General Public License #as published by the Free Software Foundation; either version 2 #of the License, or (at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. # #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import kivy kivy.require('1.9.0') from kivy.app import App from navigationDrawer import NavigationDrawer from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.properties import ObjectProperty from kivy.properties import NumericProperty from kivy.properties import ListProperty from kivy.uix.popup import Popup from kivy.lib import osc from kivy.clock import Clock from kivy.utils import platform __author__ = 'tarliton'
from vkeyboard import VKeyboard import kivy kivy.require('1.0.8') from kivy.core.window import Window from kivy.uix.textinput import TextInput from kivy.uix.floatlayout import FloatLayout from kivy.uix.scatter import Scatter from kivy.uix.button import Button from kivy.uix.label import Label from kivy.config import Config #from kivy.base import runTouchApp from kivy.app import App #from kivy.uix.settings import Settings class VKeyboardApp(App): def _keyboard_close(self): pass def build(self): Config.set('kivy', 'keyboard_mode', 'dock') Window.set_vkeyboard_class(VKeyboard) Window.configure_keyboards() root = FloatLayout() root.add_widget(TextInput()) kb = Window.request_keyboard(self._keyboard_close, self) return root
#!/usr/bin/env python """ This is the main module for the RollIt! GUI to diceroller. """ import cli_args import kivy kivy.require("1.4.1") from kivy.app import App from kivy.uix.button import Button from kivy.uix.textinput import TextInput from kivy.properties import ObjectProperty, ListProperty from kivy.uix.floatlayout import FloatLayout from kivy.uix.bubble import Bubble, BubbleButton from kivy.uix.scrollview import ScrollView from kivy.factory import Factory from kivy.clock import Clock from kivy.uix.accordion import Accordion, AccordionItem from kivy.uix.spinner import Spinner from kivy.interactive import InteractiveLauncher from kivy.logger import Logger from kivy.config import Config Config.set("kivy", "window_icon", "icon.png") Config.set("input", "mouse", "mouse,disable_multitouch") import re import rollparse from dicehelp import dice_help import pickle import traceback import sys
#!/usr/bin/env python # -*- coding: utf-8 -*- import kivy kivy.require('1.0.1') import os import sys import sqlite3 sqlite3_file = 'cascada_propietarios' cnn_db = sqlite3.connect(sqlite3_file) cursor = cnn_db.cursor() print("Open DataBase in Control_Mensualidad") import kivy from kivy.config import Config Config.set('graphics', 'width', '700') Config.set('graphics', 'height', '500') from kivy.core.window import Window Window.clearcolor = (0, 0, 0.3, 0) from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.textinput import TextInput from kivy.uix.popup import Popup import reportlab from reportlab.lib.pagesizes import letter from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.platypus import Spacer, SimpleDocTemplate, Table, TableStyle from reportlab.platypus import Paragraph, Image from reportlab.lib import colors from reportlab.lib import enums
# Set window size import kivy kivy.require('1.9.0') from kivy.config import Config Config.set('graphics', 'width', '480') Config.set('graphics', 'height', '800') # Config.set('graphics', 'width', '240') # Config.set('graphics', 'height', '400') from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.togglebutton import ToggleButton from kivy.uix.gridlayout import GridLayout from kivy.uix.widget import Widget from kivy.uix.button import Button from kivy.uix.textinput import TextInput from kivy.uix.image import Image from kivy.uix.slider import Slider from kivy.animation import Animation from kivy.properties import ListProperty, NumericProperty from kivy.clock import Clock from kivy.graphics import Color, Rectangle from kivy.metrics import dp, sp from kivy.core.window import Window from random import random
def execute_directives(self): global __KV_INCLUDES__ for ln, cmd in self.directives: cmd = cmd.strip() if __debug__: trace('Parser: got directive <%s>' % cmd) if cmd[:5] == 'kivy ': version = cmd[5:].strip() if len(version.split('.')) == 2: version += '.0' require(version) elif cmd[:4] == 'set ': try: name, value = cmd[4:].strip().split(' ', 1) except: Logger.exception('') raise ParserException(self, ln, 'Invalid directive syntax') try: value = eval(value, global_idmap) except: Logger.exception('') raise ParserException(self, ln, 'Invalid value') global_idmap[name] = value elif cmd[:8] == 'include ': ref = cmd[8:].strip() force_load = False if ref[:6] == 'force ': ref = ref[6:].strip() force_load = True if ref[-3:] != '.kv': Logger.warn('WARNING: {0} does not have a valid Kivy' 'Language extension (.kv)'.format(ref)) break if ref in __KV_INCLUDES__: if not os.path.isfile(resource_find(ref) or ref): raise ParserException( self, ln, 'Invalid or unknown file: {0}'.format(ref)) if not force_load: Logger.warn( 'WARNING: {0} has already been included!'.format( ref)) continue else: Logger.debug( 'Reloading {0} because include was forced.'.format( ref)) kivy.lang.builder.Builder.unload_file(ref) kivy.lang.builder.Builder.load_file(ref) continue Logger.debug('Including file: {0}'.format(0)) __KV_INCLUDES__.append(ref) kivy.lang.builder.Builder.load_file(ref) elif cmd[:7] == 'import ': package = cmd[7:].strip() l = package.split() if len(l) != 2: raise ParserException(self, ln, 'Invalid import syntax') alias, package = l try: if package not in sys.modules: try: mod = __import__(package) except ImportError: mod = __import__('.'.join(package.split('.')[:-1])) # resolve the whole thing for part in package.split('.')[1:]: mod = getattr(mod, part) else: mod = sys.modules[package] global_idmap[alias] = mod except ImportError: Logger.exception('') raise ParserException( self, ln, 'Unable to import package %r' % package) else: raise ParserException(self, ln, 'Unknown directive')
import kivy kivy.require('1.9.1') from kivy.app import App from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.togglebutton import ToggleButton from kivy.uix.gridlayout import GridLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.textinput import TextInput from kivy.uix.actionbar import ActionBar from kivy.uix.actionbar import ActionButton from kivy.uix.slider import Slider from kivy.uix.image import Image from kivy.uix.behaviors import ButtonBehavior from kivy.uix.behaviors import ToggleButtonBehavior from kivy.graphics import Color, Rectangle from kivy.properties import StringProperty from kivy.properties import ListProperty from kivy.properties import DictProperty from kivy.properties import ObjectProperty from kivy.properties import NumericProperty from kivy.properties import BooleanProperty from kivy.clock import Clock from kivy.storage.jsonstore import JsonStore import kivy.lib.osc.oscAPI as oscAPI
# 时间 from time import strftime # ======================================== 追加路径 ======================================== # 追加路径 from common.util.yushirui_path_append import yushirui_path_append # 追加路径 yushirui_path_append() # ======================================== kivy ======================================== # kivy import kivy # Kivy版本号 kivy.require('1.11.1') # ======================================== 查找文件 ======================================== # 查找文件 from common.util.yushirui_find_file_or_dir import yushirui_find_file_or_dir # ======================================== 指定配置文件 ======================================== # 查找配置文件 config_path = yushirui_find_file_or_dir('config/kivy_config.ini') # 读取配置,支持中文 from kivy.config import Config # 读取配置文件 Config.read(config_path) # ======================================== 设置字体 ========================================
accurate. The right way would be to get the accelerometer + magnetic, and computer everything according to the phone orientation. This is not the purpose of this example right now. You can compile it with:: ./build.py --package org.test.compass --name compass \ --private ~/code/kivy/examples/android/compass \ --window --version 1.0 debug installd ''' import kivy kivy.require('1.7.0') from jnius import autoclass from kivy.app import App from kivy.properties import NumericProperty from kivy.clock import Clock from kivy.vector import Vector from kivy.animation import Animation Hardware = autoclass('org.renpy.android.Hardware') class CompassApp(App): needle_angle = NumericProperty(0)
from kivy.config import Config Config.set('graphics', 'width', '1050') Config.set('graphics', 'height', '990') Config.set('graphics', 'resizable', False) Config.set('input', 'mouse', 'mouse,multitouch_on_demand') import kivy kivy.require("1.9.0") from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.listview import ListItemButton from kivy.properties import ObjectProperty import datetime import db_functions import sqlite3 class PrikazListButton(ListItemButton): pass class UpdatePopup(): pass class DelovneUre(BoxLayout): #Spremenljivke razreda ime_iz_vnosa = ObjectProperty() datum_iz_vnosa = ObjectProperty() prihod_iz_vnosa = ObjectProperty()
import kivy kivy.require("1.7.2") from kivy.app import App from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput class LoginScreen(GridLayout): def __init__(self, **kwargs): super(LoginScreen, self).__init__(**kwargs) self.cols = 2 self.add_widget(Label(text="user_name")) self.username = TextInput(multiline=False) self.add_widget(self.username) self.add_widget(Label(text="password")) self.password = TextInput(password=True, multiline=False) self.add_widget(self.password) class MyApp(App): def build(self): return LoginScreen() if __name__ == "__main__": MyApp().run()
import os os.environ['KIVY_GL_BACKEND'] = 'angle_sdl2' from kivy import Config Config.set('graphics', 'multisamples', '0') import kivy kivy.require('1.9.1') import glob import webbrowser from random import randint from os.path import join, dirname from kivy.app import App from kivy.logger import Logger from kivy.uix.scatter import Scatter from kivy.properties import StringProperty from kivy.uix.button import Button from kivy.uix.image import Image from kivy.uix.label import Label from kivy.uix.behaviors import ButtonBehavior from kivy.uix.floatlayout import FloatLayout from kivy.uix.relativelayout import RelativeLayout class Picture(Scatter): '''Picture is the class that will show the image with a white border and a shadow. They are nothing here because almost everything is inside the picture.kv. Check the rule named <Picture> inside the file, and you'll see how the Picture() is really constructed and used.