Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - AnchorLayout ใน Kivy


Kivy เป็นไลบรารี Python แบบโอเพ่นซอร์สสำหรับการพัฒนาแอปพลิเคชันอย่างรวดเร็วซึ่งใช้ประโยชน์จากอินเทอร์เฟซผู้ใช้ที่เป็นนวัตกรรมใหม่ เช่น แอปมัลติทัช มันถูกใช้เพื่อพัฒนาแอปพลิเคชัน Android เช่นเดียวกับแอปพลิเคชันเดสก์ท็อป ในบทความนี้เราจะมาดูวิธีการใช้การวางตำแหน่งของจุดยึด

การใช้ AnchorLayouts เราวางวิดเจ็ตไว้ที่ขอบด้านใดด้านหนึ่ง คลาส kivy.uix.anchorlayout.AnchorLayout ใช้โครงร่างสมอ ทั้งพารามิเตอร์ anchor_x และพารามิเตอร์ anchor_y สามารถส่งผ่านค่า "left", "right" และ "center" ได้ ในโปรแกรมด้านล่าง เราสร้างปุ่มสองปุ่ม ติดไว้กับจุดยึดสองตัว และเก็บไว้ใน BoxLayout

ตัวอย่าง

from kivy.app import App
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
class AnchorLayoutApp(App):
   def build(self):
      # Anchor Layout1
      anchor1 = AnchorLayout(anchor_x='left', anchor_y='bottom')
      button1 = Button(text='Bottom-Left', size_hint=(0.3, 0.3),background_color=(1.0, 0.0, 0.0, 1.0))
      anchor1.add_widget(button1)
      # Anchor Layout2
      anchor2 = AnchorLayout(anchor_x='right', anchor_y='top')
      # Add anchor layouts to a box layout
      button2 = Button(text='Top-Right', size_hint=(0.3, 0.3),background_color=(1.0, 0.0, 0.0, 1.0))
      anchor2.add_widget(button2)
      # Create a box layout
      BL = BoxLayout()
      # Add both the anchor layouts to the box layout
      BL.add_widget(anchor1)
      BL.add_widget(anchor2)
      # Return the boxlayout widget
      return BL
# Run the Kivy app
if __name__ == '__main__':
   AnchorLayoutApp().run()

การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -

ผลลัพธ์

Python - AnchorLayout ใน Kivy