Python | Diseño relativo en Kivy usando un archivo .kv

Kivy es una herramienta GUI independiente de la plataforma en Python. Como se puede ejecutar en Android, IOS, Linux y Windows, etc. Básicamente se usa para desarrollar la aplicación de Android, pero eso no significa que no se pueda usar en aplicaciones de escritorio.

👉🏽 Tutorial de Kivy: aprenda Kivy con ejemplos .

Disposición relativa:

  • Este diseño funciona de la misma manera que FloatLayout, pero las propiedades de posicionamiento (x, y, center_x, right, y, center_y y top) son relativas al tamaño del diseño y no al tamaño de la ventana.
  • En realidad, independientemente del posicionamiento absoluto y relativo, los widgets se mueven cuando cambia la posición del diseño.
  • Las teclas pos_hint disponibles (x, center_x, right, y, center_y y top) son útiles para alinear los bordes o centrar.
    Por ejemplo:
    pos_hint: {‘center_x’:.5, ‘center_y’:.5} alinearía un Widget en el medio, sin importar el tamaño de la ventana.

Lo primero que debemos hacer para usar un RelativeLayout es importarlo.

from kivy.uix.relativelayout import RelativeLayout

Podemos hacer posicionamiento relativo por:
pos_hint: proporciona una pista de posición.

Podemos definir hasta 8 claves, es decir, toma argumentos en forma de diccionario.
pos_hint = {“x”:1, “y”:1, “izquierda”:1, “derecha”:1, “center_x”:1, “center_y”:1, “arriba”:1, “abajo”:1 («superior»: 0)}

Nota:
Floatlayout y RelativeLayout admiten el posicionamiento absoluto y relativo dependiendo de si se usa pos_hint o pos. Pero si desea un posicionamiento absoluto, use FloatLayout.

Basic Approach to create Relative Layout:
1) import kivy
2) import kivy App
3) import Relativelayout
4) Set minimum version(optional)
5) create class for layout 
6) create App class:
        - define build() function
7) Set up.kv file(name same ass the App class)
8) return Layout Class
9) Run an instance of the class

 
A continuación se muestra la implementación:

archivo principal.py

## Sample Python application demonstrating the 
## working of RelativeLayout in Kivy using .kv file 
  
################################################### 
# import modules 
  
import kivy 
  
# base Class of your App inherits from the App class. 
# app:always refers to the instance of your application 
from kivy.app import App 
  
# This layout allows you to set relative coordinates for children.
from kivy.uix.relativelayout import RelativeLayout
  
# To change the kivy default settings 
# we use this module config 
from kivy.config import Config 
      
# 0 being off 1 being on as in true / false 
# you can use 0 or 1 && True or False 
Config.set('graphics', 'resizable', True) 
  
  
# creating the root widget used in .kv file 
class RelativeLayout(RelativeLayout): 
    pass
  
# creating the App class in which name 
#.kv file is to be named Relative_Layout.kv 
class Relative_LayoutApp(App): 
    # defining build() 
    def build(self): 
        # returning the instance of root class 
        return RelativeLayout() 
  
# run the app 
if __name__ == "__main__": 
    Relative_LayoutApp().run() 

Implementación del archivo .kv :

#.kv file implementation of RelativeLayout 
  
# creating button feature 
<Button>:
        # size of text on button
        font_size: 20
              
        # creating button 
        # a button 20 % of the width and 20 % 
        # of the height of the layout 
        size_hint: 0.2, 0.2
  
<RelativeLayout>:
  
        # The Canvas is the root object
        # used for drawing by a Widget. 
  
        canvas:
                Color:
                        rgb:0, 1, 1
                Rectangle:
                        # creating rectangle
                        # pos = 20 % and size = 60 % of the layout
                        pos:[0.2 * coord for coord in self.size]
                        size:[0.6 * coord for coord in self.size]
  
  
        # creating the button
  
        Button:
              
                text:"B1"
  
                background_color: 0.1, 0.5, 0.6, 1
              
                # positioned at 0 % in x axis and 0 % in y axis 
                # from bottom left, i.e x, y = 0, 0 from bottom left: 
                pos_hint: {"x":0, "y":0} 
  
        Button: 
                text:"B2"
                background_color: 1, 0, 0, 1
                pos_hint: {"right":1, "y":0} 
  
                      
        Button: 
                text:"Yash"
                background_color: 0.4, 0.5, 0.6, 1
                pos_hint: {"center_x":.5, "center_y":.5} 
  
        Button: 
                text:"B3"
                background_color: 0, 0, 1, 1
                pos_hint: {"x":0, "top":1} 
  
        Button: 
                text:"B4"
                background_color: 0.8, 0.9, 0.2, 1
                pos_hint: {"right":1, "top":1} 

Producción:

Hay diferentes tamaños de imágenes de ventana que muestran cómo se ajusta de acuerdo con la ventana, es decir, relativamente

Imagen 1:

Imagen 2:

Imagen 3:

Referencia: https://kivy.org/doc/stable/api-kivy.uix.relativelayout.html

Publicación traducida automáticamente

Artículo escrito por YashKhandelwal8 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *