[Python] KivyMd Does not maintain the MDCards aspect ration and Problems in Size_hint_Y

Discussão em 'Python' iniciado por Stack, Fevereiro 17, 2025.

  1. Stack

    Stack Membro Participativo

    As the title suggests, my kivy application is facing a lot of problems that chatgpt could not solve. The problem occured becuase of the vertical scrollbars. My main problem is the MDCards does maintain its aspect ratio when resizing the screen, and secondly, I want the first row to have 0.3 size_hint_y, the second is 0.45 and the bottom 0.1 But I could not make it work. Here is the Python Program:

    import os
    import sys
    import logging
    from kivy.config import Config
    from kivy.lang import Builder
    from kivy.uix.floatlayout import FloatLayout
    from kivymd.app import MDApp
    from kivy.app import App
    from kivy.core.window import Window
    from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg
    import matplotlib.pyplot as plt

    # First Line Chart
    x1 = [1, 2, 3, 4, 5]
    y1 = [5, 12, 6, 9, 15]
    fig1, ax1 = plt.subplots(figsize=(4, 3))
    ax1.plot(x1, y1, marker='o', linestyle='-', color='b', label="Graph 1")
    ax1.set_ylabel("Y Axis")
    ax1.set_xlabel("X Axis")
    ax1.legend()
    ax1.set_facecolor("#f0f0f0") # Light gray background

    # Second Line Chart
    x2 = [1, 2, 3, 4, 5]
    y2 = [8, 3, 10, 7, 6]
    fig2, ax2 = plt.subplots(figsize=(4, 3))
    ax2.plot(x2, y2, marker='s', linestyle='--', color='r', label="Graph 2")
    ax2.set_ylabel("Y Axis")
    ax2.set_xlabel("X Axis")
    ax2.legend()
    ax2.set_facecolor("#f5e1d2") # Light brown background

    # Bar Chart
    categories = ['A', 'B', 'C', 'D']
    values = [4, 7, 1, 8]
    fig3, ax3 = plt.subplots(figsize=(4, 3))
    ax3.bar(categories, values, color=['blue', 'green', 'red', 'purple'])
    ax3.set_ylabel("Values")
    ax3.set_title("Bar Chart")
    ax3.set_facecolor("#e0e0e0") # Light gray background

    # Pie Chart
    labels = ['Apple', 'Banana', 'Cherry', 'Date']
    sizes = [30, 20, 35, 15]
    fig4, ax4 = plt.subplots(figsize=(4, 3))
    ax4.pie(sizes, labels=labels, autopct='%1.1f%%', colors=['red', 'yellow', 'pink', 'brown'])
    ax4.set_title("Pie Chart")
    ax4.set_facecolor("#ffebcd") # Light peach background

    class Matty(FloatLayout):
    def __init__(self, **kwargs):
    super().__init__(**kwargs)

    # Add first line chart
    self.ids.chart1.add_widget(FigureCanvasKivyAgg(fig1))

    # Add second line chart
    self.ids.chart2.add_widget(FigureCanvasKivyAgg(fig2))

    # Add bar chart
    self.ids.chart3.add_widget(FigureCanvasKivyAgg(fig3))

    # Add pie chart
    self.ids.chart4.add_widget(FigureCanvasKivyAgg(fig4))

    # Bind window resize event to dynamically adjust layout
    Window.bind(on_resize=self.update_orientation)

    def update_orientation(self, instance, width, height):
    """Change layout orientation based on screen ratio."""
    if height > 1.35 * width: # If height is 2x the width, switch to vertical
    self.ids.box.orientation = "vertical"
    self.ids.box2.orientation = "vertical"
    self.ids.card1.size_hint_x = 1
    self.ids.card2.size_hint_x = 1
    self.ids.card3.size_hint_x = 1
    self.ids.card4.size_hint_x = 1
    else:
    self.ids.box.orientation = "horizontal"
    self.ids.box2.orientation = "horizontal"
    self.ids.card1.size_hint_x = 0.5
    self.ids.card2.size_hint_x = 0.5
    self.ids.card3.size_hint_x = 0.5
    self.ids.card4.size_hint_x = 0.5

    def close_app(self):
    App.get_running_app().stop()
    Window.close()

    class MyApp(MDApp):
    def build(self):
    self.theme_cls.theme_style = "Light"
    self.theme_cls.primary_palette = "BlueGray"
    Builder.load_file('matty.kv')
    Window.bind(on_request_close=self.on_request_close)
    return Matty()

    def on_request_close(self, *args):
    App.get_running_app().stop()
    Window.close()
    return True

    if __name__ == '__main__':
    MyApp().run()


    And here is the.kv File:

    <Matty>:
    MDBoxLayout:
    orientation: "vertical"

    # Top App Bar
    MDTopAppBar:
    title: "My App with Charts"
    elevation: 10

    # Scrollable area for charts
    ScrollView:
    do_scroll_x: False
    do_scroll_y: True

    MDBoxLayout:
    orientation: "vertical"
    size_hint_y: None
    height: self.minimum_height
    spacing: 10
    padding: 10

    # First row of charts (Line Charts)
    BoxLayout:
    id: box
    orientation: "horizontal"
    size_hint_y: None
    height: dp(250)
    spacing: 10
    padding: 10

    # First Chart (Gray Background)
    MDCard:
    id: card1
    size_hint_x: 0.5
    md_bg_color: 0.5, 0.5, 0.5, 1 # Gray
    radius: [20, 20, 20, 20]
    elevation: 5
    padding: 20
    BoxLayout:
    id: chart1
    orientation: "vertical"
    padding: 15
    spacing: 10

    # Second Chart (Brown Background)
    MDCard:
    id: card2
    size_hint_x: 0.5
    md_bg_color: 0.6, 0.3, 0.1, 1 # Brown
    radius: [20, 20, 20, 20]
    elevation: 5
    padding: 20
    BoxLayout:
    id: chart2
    orientation: "vertical"
    padding: 15
    spacing: 10

    # Second row of charts (Bar and Pie Charts)
    BoxLayout:
    id: box2
    orientation: "horizontal"
    size_hint_y: None
    height: dp(250)
    spacing: 10
    padding: 10

    # Third Chart (Bar Chart - Light Gray Background)
    MDCard:
    id: card3
    size_hint_x: 0.5
    md_bg_color: 0.7, 0.7, 0.7, 1 # Light Gray
    radius: [20, 20, 20, 20]
    elevation: 5
    padding: 20
    BoxLayout:
    id: chart3
    orientation: "vertical"
    padding: 15
    spacing: 10

    # Fourth Chart (Pie Chart - Light Peach Background)
    MDCard:
    id: card4
    size_hint_x: 0.5
    md_bg_color: 1, 0.85, 0.7, 1 # Light Peach
    radius: [20, 20, 20, 20]
    elevation: 5
    padding: 20
    BoxLayout:
    id: chart4
    orientation: "vertical"
    padding: 15
    spacing: 10

    # Input and Close Button
    BoxLayout:
    size_hint_y: None
    height: dp(50)
    padding: 10
    spacing: 10

    TextInput:
    id: namer
    multiline: False
    hint_text: "Enter something"

    Button:
    text: "Close App"
    on_release: root.close_app()


    this is the normal screen: [​IMG]

    and here is the problematic screen: [​IMG]

    Continue reading...

Compartilhe esta Página