Skip to content

Instantly share code, notes, and snippets.

@Franck1333
Last active October 31, 2019 15:07
Show Gist options
  • Select an option

  • Save Franck1333/01f4047bd53ece4ebf439de68b06dad4 to your computer and use it in GitHub Desktop.

Select an option

Save Franck1333/01f4047bd53ece4ebf439de68b06dad4 to your computer and use it in GitHub Desktop.
Learning about Kivy UI
#AIDES: riptutorial.com/fr/kivy
from kivy.app import App
from kivy.uix.button import Button
class TutorialApp(App):
def build(self):
return Button(text="Coucou Bande de Nouilles!")
TutorialApp().run()
# -*- coding: utf-8 -*-
#Aides: https://kivy.org/doc/stable/guide/lang.html #Documenation sur la Synthax a avoir
#Aides: https://kivy.org/doc/stable/api-kivy.uix.label.html #Documentation sur les differents Widgets de base de Kivy
#Aides: https://kivy.org/doc/stable/api-kivy.uix.boxlayout.html #Documentation sur le Layout (couche) dit 'BoxLayout' de Kivy
#---------------------------------------Importante LIB---------------------------------------
import os #Blibliotheque permettant l'interaction avec le systeme
import sys #Blibliotheque permettant l'interaction avec le systeme
import datetime #Blibliotheque permettant d'obtenir la date
import time #Blibliotheque permettant d'obtenir la date
#---------------------------------------Importante LIB---------------------------------------
from kivy.app import App
#from kivy.uix.boxlayout import BoxLayout
from kivy.uix.anchorlayout import AnchorLayout
# BoxLayout: it's in the python part, so you need to import it
from kivy.uix.widget import Widget
from kivy.properties import StringProperty
from kivy.clock import Clock
from kivy.lang import Builder
Builder.load_string(""" #Pour gérer la partie KV soit on ecrit le contenue directement dans cette methode de cette facon ou alors on renseigne de cette meme facon un fichier local avec ce contenue
#Lorque le language KV est utiliser, il est pas necessaire d'importer quoi que ce soit.
<MaDisposition>
AnchorLayout:
anchor_x: 'center'
anchor_y: 'top'
Label: #WIDGET Permettant l'affichage d'un mot/phrase
id:text_label #Identifiant permettant a ce label d'etre accessible via le code python
text_language: "fr" #Ligne permettant de connaitre la langue utiliser dans ce label
text: root.Time_Horloge #Valeur qui doit etre afficher a l'ecran
bold: False #Parametre permettant de mettre en gras un label
italic: False #Permet de mettre en italique le contenue du label
underline : False #Permet de souligner le contenue du label
color: (13,1,1,1) #Parametre permettant d'ajouter de la couleur a un label
""")
class MaDisposition(AnchorLayout):
Time_Horloge = StringProperty() #On indiquand que Time_Horloge a une Propietee STRING, cela indique au system que cette variable devra etre mise à jour
#par rapport a l'interface lors de son changement de valeur.
def __init__(self, **kwargs): #Pour mettre a jour un contenue, il faut l'inserer dans cette fonction precise
super(MaDisposition, self).__init__(**kwargs) #On SuperCharge la classe de cette facon.
#---Element a Mettre a jour---
Clock.schedule_interval(self.temps_actuel_update,1) #Et grace a Clock.schedule_interval(fonction, X secondes), on trigger la mise a jour
#---Element a Mettre a jour---
#---------------------------------------------
def temps_actuel(self):
#OBTENTION DE L'HEURE ACTUEL sous format HEURE,MINUTE,SECONDE
#-- DEBUT -- Heure,Minute,Seconde
tt = time.time()
system_time = datetime.datetime.fromtimestamp(tt).strftime('%H:%M:%S')
print(("Voici l'heure:",system_time))
return system_time
#-- FIN -- Heure,Minute,Seconde
def temps_actuel_update(self, *args): #On oublie pas de mentionner l'argument '*args', pour eviter l'erreur {AttributeError: 'float' object has no attribute}.
self.Time_Horloge = MaDisposition.temps_actuel(self)
#---------------------------------------------
class CryptoWatchApp(App):
def on_start(self):
pass
def on_stop(self):
pass
def build(self):
return MaDisposition()
if __name__ == "__main__":
CryptoWatchApp().run()
#AIDES: riptutorial.com/fr/kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
class TutorialApp(App):
def build(self):
mylayout = BoxLayout(orientation="vertical")
mylabel = Label(text="My App enfaite")
mybutton = Button(text="Click sur ce bouton!")
mylayout.add_widget(mylabel)
mybutton.bind(on_press = lambda a:print(mylabel.text))
mylayout.add_widget(mybutton)
return mylayout
TutorialApp().run()
#AIDES: riptutorial.com/fr/kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
# BoxLayout: it's in the python part, so you need to import it
from kivy.lang import Builder
Builder.load_string("""
<MyLayout>
orientation:"vertical"
Label: # it's in the kv part, so no need to import it
id:mylabel
text:"My App"
Button:
text: "Click me!"
on_press: print(mylabel.text)
""")
class MyLayout(BoxLayout):
pass
class TutorialApp(App):
def build(self):
return MyLayout()
TutorialApp().run()
#AIDES: riptutorial.com/fr/kivy
# A line used mostly as the first one, imports App class
# that is used to get a window and launch the application
from kivy.app import App
# Casual Kivy widgets that reside in kivy.uix
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.screenmanager import SlideTransition
# Inherit Screen class and make it look like
# a simple page with navigation
class CustomScreen(Screen):
# It's necessary to initialize a widget the class inherits
# from to access its methods such as 'add_widget' with 'super()'
def __init__(self, **kwargs):
# Py2/Py3 note: although in Py3 'super()' is simplified
# it's a good practice to use Py2 syntax, so that the
# code is compatibile in both versions
super(CustomScreen, self).__init__(**kwargs)
# Put a layout in the Screen which will take
# Screen's size and pos.
# The 'orientation' represents a direction
# in which the widgets are added into the
# BoxLayout - 'horizontal' is the default
layout = BoxLayout(orientation='vertical')
# Add a Label with the name of Screen
# and set its size to 50px
layout.add_widget(Label(text=self.name, font_size=50))
# Add another layout to handle the navigation
# and set the height of navigation to 20%
# of the CustomScreen
navig = BoxLayout(size_hint_y=0.2)
# Create buttons with a custom text
prev = Button(text='Previous')
next = Button(text='Next')
# Bind to 'on_release' events of Buttons
prev.bind(on_release=self.switch_prev)
next.bind(on_release=self.switch_next)
# Add buttons to navigation
# and the navigation to layout
navig.add_widget(prev)
navig.add_widget(next)
layout.add_widget(navig)
# And add the layout to the Screen
self.add_widget(layout)
# *args is used to catch arguments that are returned
# when 'on_release' event is dispatched
def switch_prev(self, *args):
# 'self.manager' holds a reference to ScreenManager object
# and 'ScreenManager.current' is a name of a visible Screen
# Methods 'ScreenManager.previous()' and 'ScreenManager.next()'
# return a string of a previous/next Screen's name
self.manager.transition = SlideTransition(direction="right")
self.manager.current = self.manager.previous()
def switch_next(self, *args):
self.manager.transition = SlideTransition(direction="right")
self.manager.current = self.manager.next()
class ScreenManagerApp(App):
# 'build' is a method of App used in the framework it's
# expected that the method returns an object of a Kivy widget
def build(self):
# Get an object of some widget that will be the core
# of the application - in this case ScreenManager
root = ScreenManager()
# Add 4 CustomScreens with name 'Screen <order>`
for x in range(4):
root.add_widget(CustomScreen(name='Screen %d' % x))
# Return the object
return root
# This is only a protection, so that if the file
# is imported it won't try to launch another App
if __name__ == '__main__':
# And run the App with its method 'run'
ScreenManagerApp().run()
#AIDES: riptutorial.com/fr/kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
# Create both screens. Please note the root.manager.current: this is how
# you can control the ScreenManager from kv. Each screen has by default a
# property manager that gives you the instance of the ScreenManager used.
Builder.load_string("""
<MenuScreen>:
BoxLayout:
Button:
text: 'First Button on Menu'
on_press: root.manager.current = 'settings'
Button:
text: 'Second Button on Menu'
<SettingsScreen>:
BoxLayout:
Button:
text: 'First Button on Settings'
on_press: root.manager.current = 'menu'
Button:
text: 'Second Button on Settings'
""")
# Declare both screens
class MenuScreen(Screen):
pass
class SettingsScreen(Screen):
pass
# Create the screen manager
sm = ScreenManager()
sm.add_widget(MenuScreen(name='menu'))
sm.add_widget(SettingsScreen(name='settings'))
class TestApp(App):
def build(self):
return sm
if __name__ == '__main__':
TestApp().run()
#Aides: https://kivy.org/doc/stable/guide/lang.html #Documenation sur la Synthax a avoir
#Aides: https://kivy.org/doc/stable/api-kivy.uix.label.html #Documentation sur les differents Widgets de base de Kivy
#Aides: https://kivy.org/doc/stable/api-kivy.uix.boxlayout.html #Documentation sur le Layout (couche) dit 'BoxLayout' de Kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
# BoxLayout: it's in the python part, so you need to import it
from kivy.lang import Builder #La Partie KV gérant l'agencement de l'Interface est gérer par cette bibliothèque
Builder.load_string(""" #Pour gérer la partie KV soit on ecrit le contenue directement dans cette methode de cette facon ou alors on renseigne de cette meme facon un fichier local avec ce contenue
<MyLayout>
#Lorque le language KV est utiliser, il est pas necessaire d'importer quoi que ce soit.
orientation:"vertical" #Definition de l'orientation du contenue
#orientation: "horizontal"
Label: #WIDGET Permettant l'affichage d'un mot/phrase
id:text_label #Identifiant permettant a ce label d'etre accessible via le code python
text_language: "fr" #Ligne permettant de connaitre la langue utiliser dans ce label
text:"My App" #Valeur qui doit etre afficher a l'ecran
bold: False #Parametre permettant de mettre en gras un label
italic: False #Permet de mettre en italique le contenue du label
underline : False #Permet de souligner le contenue du label
color: (13,1,1,1) #Parametre permettant d'ajouter de la couleur a un label
Button: #WIDGET Permettant l'affichage d'un Bouton avec lequel interagir
id: Bouton_01 #Identifiant permettant a ce label d'etre accessible via le code python
text: "Click moe!" #Valeur qui sera imprime sur le bouton lors de son apparition
background_color: (2,1,2,1) #Valeur permettant de coloriser le bouton
pos_hint: {'center_x': 0.5, 'center_y': 0.705} #On choisi sa position dans l'espace
size_hint: 0.350, 0.350 #On choisi la taille du bouton
on_press: print(text_label.text) #Lorsque le bouton sera presser par l'utilisateur, alors Kivy affichera le champ text actuel du label
on_release: root.Changer_label() #Lorsque le bouton sera relacher par l'Utilisateur, alors Kivy lancera une fonction permetant de cet exemple de modifier le contenue text du Label
on_state:
print("Mon etat est {}".format(self.state)) #Lorque le bouton changera d'etat, une action peut etre realiser;
#a chaque fois que le bouton changera d'etat soit quand l'utilisateur utilise le bouton, l'état du Bouton sera affiche dans la console
Image: #WIDGET utile pour afficher une image avec Kivy
id: Emplacement_Image_01 #Identifiant permettant a ce label d'etre accessible via le code python
source: 'Versaille.jpg' #Parametre indiquant la source de l'image concernee
keep_ratio: True #Garder le Ration de l'image pour l'affichage
keep_data: True #Garder les informations de l'image en mémoire
TextInput:
id: Entree_texte_01 #Identifiant permettant a ce label d'etre accessible via le code python
size_hint: 0.350, 0.350 #On choisi la taille du bouton
pos_hint: {'center_x': 0.505, 'center_y': 0.705} #On choisi sa position dans l'espace
allow_copy: True #Autorise le copier/coller
auto_indent: True #Kivy peut automatiquement indenter le contenue de l'entree
cursor_blink: True #Le curseur quand il sera place dans l'entree; il clignotera pour annoncer sa presence
keyboard_suggestions : True #Les clavier intelligent pourront presenter a l'utilisateur des mots a suggerer a entree
""")
class MyLayout(BoxLayout):
#---Acceder/Modifier une valeur d'un element visuel---
def Changer_label(self):
self.ids["text_label"].text = "Prend mon Zboub !"
#Pour acceder/modifier les valeurs d'un widget, il faut creer une fonction avec en parametre l'object (SELF) comme ci-dessus,
#Et appeler cette fonction comme ceci : root.fonction1()
#---Acceder/Modifier une valeur d'un element visuel---
class OutilsApp(App):
def build(self):
return MyLayout()
OutilsApp().run()
#AIDES: riptutorial.com/fr/kivy
from kivy.app import App
from kivy.uix.button import Button
class Mybutton(Button):
text="Click me!"
on_press = lambda a : print("My Button")
class TutorialApp(App):
def build(self):
return Mybutton()
TutorialApp().run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment