Как заставить size_hint_x начинаться с 0,2 вместо 0 в Kivy?

У меня есть много столбцов, которые нужно показать с помощью макета5. Поскольку приложение будет отображаться на экранах разных размеров, я использовал Layout5.bind(minimum_width=layout5.setter('width')) для установки ширины. Примечательно, что родительским элементом Layout5 является Scroll3 с pos_hint={'x':0.2,'y':0.02}. Это означает, что мои столбцы начинают отображаться с x = 0,2. Проблема: layout5.bind(minimum_width=layout5.setter('width')) вычисляет минимальную ширину от 0 вместо 0,2, поэтому я не вижу всех столбцов.

Вопрос: как я могу убедиться, чтоlayout5.bind(minimum_width=layout5.setter('width'))принимает во внимание тот факт, что ось X родительского виджета (scroll3) начинается с 0,2?

Примечание:

  1. Я отметил звездочками те части кода, на которых следует сосредоточить внимание.
  2. При запуске кода просто заменитеScreen1.csvс любым CSV-файлом на вашем компьютере.

Полный код:

      from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.uix.gridlayout import GridLayout
import pandas as pd
from kivy.uix.scrollview import ScrollView
from kivy.uix.label import Label
from kivymd.uix.anchorlayout import MDAnchorLayout
from kivymd.uix.button import MDRoundFlatButton
from kivymd.app import MDApp



class Screen1 (Screen):
    def __init__(self, **kwargs):
        super(Screen1, self).__init__(**kwargs)

        # Reading Data
        data1 = pd.read_csv('Screen1.csv')

        # row range
        rows1 = range(3, 29)

        # column range
        cols1 = range(4, 74)


        layout0 = GridLayout(cols=1, rows=1, size_hint=(0.18, 1.79))
        layout0.bind(minimum_height=layout0.setter('height'))
        self.add_widget(layout0)
        label0 = Label(text="Train Station           Platform", bold=True)
        layout0.bind(minimum_width=layout0.setter('width'))
        layout0.add_widget(label0)

        # Creating the Stations names and their respective platforms
        cols10 = range(1, 3)
        layout10 = GridLayout(cols=len(cols10), rows=len(rows1), size_hint=(1, None), row_default_height=50, spacing=10,
                              row_force_default=True)
        layout10.bind(minimum_height=layout10.setter('height'))
        # 2.65
        scroll1 = ScrollView(do_scroll_x=False, do_scroll_y=True, size_hint=(0.20, 0.84),
                             bar_color=(0, 0, 0, 0), bar_inactive_color=(0, 0, 0, 0))
        scroll1.add_widget(layout10)
        self.add_widget(scroll1)

        for row in rows1:
            for col in cols10:
                selected = str(data1.iloc[row, col])
                label10 = Label(text=selected, color=(1, 1, 1, 1), opacity=1)
                layout10.add_widget(label10)

        # Creating the back button
        layout1 = MDAnchorLayout(anchor_x='left', anchor_y='top')
        self.add_widget(layout1)

        button1 = MDRoundFlatButton(text='Back', line_color=(1, 1, 1, 1), text_color=(1, 1, 1, 1), _min_height=30,
                                    _min_width=100)
        #button1.fbind('on_press', self.Screen2)
        layout1.add_widget(button1)

        # Creating the title label
        layout2 = GridLayout(cols=1, rows=1, size_hint_y=1.93, size_hint_x=1.1)
        self.add_widget(layout2)

        label2 = Label(text="KwaMashu to Durban to Umlazi", bold=True, font_size=20)
        layout2.add_widget(label2)

        # Creating the train numbers
        rows2 = range(1, 2)
        layout4 = GridLayout(cols=len(cols1), rows=len(rows2), size_hint_x=None, size_hint_y=1, col_default_width=100,
                             col_force_default=True, spacing=10)
        layout4.minimum_width = len(cols1)
        layout4.bind(minimum_width=layout4.setter('width'))
      
        scroll2 = ScrollView(do_scroll_x=True, do_scroll_y=False, size_hint_y=1.74, pos_hint={'x': 0.20, 'y': 0.02},
                             bar_inactive_color=(0, 0, 0, 0), bar_color=(0, 0, 0, 0))
        scroll2.add_widget(layout4)
        # pos_hint = {'x': 0.20, 'y': 0.02},
        self.add_widget(scroll2)
        for row in rows2:
            for col in cols1:
                df1 = data1.iloc[row, col]
                label8 = Label(text=str(df1), bold=True)
                layout4.add_widget(label8)

        # Creating the timetable label

        
#Important***
        layout5 = GridLayout(cols=len(cols1), rows=len(rows1), size_hint_x=(None), size_hint_y=None,
                             col_default_width=100, col_force_default=True,
                             row_default_height=50, spacing=10, row_force_default=True)
        layout5.bind(minimum_height=layout5.setter('height'))
        layout5.bind(minimum_width=layout5.setter('width'))

#Important***
        scroll3 = ScrollView(size_hint=(1, 0.84), pos_hint={'x': 0.2, 'y': 0.02},
                             bar_inactive_color=(0, 0, 0, 0), bar_color=(0, 0, 0, 0))
        scroll3.add_widget(layout5)
        self.add_widget(scroll3)

        for row in rows1:
            for col in cols1:
                df = data1.iloc[row, col]
                label5 = Label(text=str(df), color=(0.75, 0.75, 0.75, 1))

                layout5.add_widget(label5)

        # Timetable and train numbers (X move together, not Y)
        scroll3.bind(scroll_x=lambda instance, value: setattr(scroll2, 'scroll_x', scroll3.scroll_x))
        scroll2.bind(scroll_x=lambda instance, value: setattr(scroll3, 'scroll_x', scroll2.scroll_x))

        # Timetable and Train Stations names (Y move together, not X)
        scroll3.bind(scroll_y=lambda instance, value: setattr(scroll1, 'scroll_y', scroll3.scroll_y))
        scroll1.bind(scroll_y=lambda instance, value: setattr(scroll3, 'scroll_y', scroll1.scroll_y))

class SuperApp (MDApp):
    def build(self):
        self.theme_cls.theme_style='Dark'
        screen_manager=ScreenManager()
        screen_manager.add_widget(Screen1(name='Screen1'))
        return screen_manager

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

1 ответ

Ваш прокрутка3 имеет size_hint=(1, 0,84). Это означает, что ширина прокрутки3 равна всей ширине вашего экрана Screen1. Однако ваш pos_hint помещает прокрутку3 со значением x, которое составляет 20% ширины экрана. Это означает, что правые 20% прокрутки3 находятся за пределами экрана. Попробуйте изменить size_hint для прокрутки3 на size_hint=(0,8, 0,84). Возможно, у вас возникнут аналогичные проблемы в другом месте.

Другие вопросы по тегам