📜  Python| Kivy中的AnchorLayout

📅  最后修改于: 2022-05-13 01:55:25.777000             🧑  作者: Mango

Python| Kivy中的AnchorLayout

Kivy 是Python中一个独立于平台的 GUI 工具。因为它可以在Android、IOS、linux和Windows等平台上运行。它基本上是用来开发Android应用程序的,但这并不意味着它不能在桌面应用程序上使用。

锚点布局:

AnchorLayout 将其子项与边框(上、下、左、右)或中心对齐。下面给出的类用于实现锚布局。

kivy.uix.anchorlayout.AnchorLayout

AnchorLayout 可以用参数初始化:

anchor_x
Parameters can be passed: “left”, “right” and “center”.

anchor_y
Parameters can be passed:“top”,  “bottom” and “center”.

选择小部件在父容器中的放置位置。

注意:请记住将多个小部件添加到锚布局,仅将小部件放置在同一位置。

Basic Approach:

1) import kivy
2) import kivyApp
4) import Anchorlayout
5) Set minimum version(optional)
6) create App class
7) return Layout/widget/Class(according to requirement)
8) Run an instance of the class


该方法的实施(带有一些样式):

1)anchor_x='right',anchor_y='bottom':

# Sample Python application demonstrating
# the working of AnchorLayout in Kivy
  
# Module imports
  
# base Class of your App inherits from the App class. 
# app:always refers to the instance of your application 
from kivy.app import App
  
# The AnchorLayout aligns its children to a border
# (top, bottom, left, right) or center
from kivy.uix.anchorlayout import AnchorLayout
  
# BoxLayout arranges children in a vertical or horizontal box.
# or help to put the childrens at the desired location.
from kivy.uix.boxlayout import BoxLayout
  
# creates the button in kivy 
# if not imported shows the error
from kivy.uix.button import Button
  
  
# A Kivy app demonstrating the working of anchor layout
class AnchorLayoutApp(App):
      
    def build(self):
  
          
        # Anchor Layout1
        layout = AnchorLayout(
        anchor_x ='right', anchor_y ='bottom')
        btn = Button(text ='Hello World',
                     size_hint =(.3, .3),
                     background_color =(1.0, 0.0, 0.0, 1.0))
      
        layout.add_widget(btn)
        return layout 
  
# creating the object root for AnchorLayoutApp() class  
root = AnchorLayoutApp()
# Run the Kivy app
root.run()

输出:

如果要更改AnchorLayouts的位置,只需将上面代码中的类代码替换为下面的代码,或者您可以将anchor_x和 anchor_y 更改为任何参数,以进行上述任意 9 种组合。

2)anchor_x='right',anchor_y='top':

# A Kivy app demonstrating the working of anchor layout
class AnchorLayoutApp(App):
      
    def build(self):
          
        # Anchor Layout1
        layout = AnchorLayout(
        anchor_x ='right', anchor_y ='top')
        btn = Button(text ='Hello World',
                     size_hint =(.3, .3),
                     background_color =(1.0, 0.0, 1.0, 1.0))
      
        layout.add_widget(btn)
        return layout 

输出:

3)anchor_x='center',anchor_y='top':
输出:

4)anchor_x='left',anchor_y='top':
输出:

5)anchor_x='left',anchor_y='bottom':
输出:

6)anchor_x='left',anchor_y='center':
输出:

7)anchor_x='center',anchor_y='center':
输出:

8)anchor_x='中心',anchor_y='底部':
输出:

9)anchor_x='right',anchor_y='center':
输出: