Почему фигуры, нарисованные на холсте, не отображаются в одном столбце kivy? - PullRequest
0 голосов
/ 06 июня 2019

Я пытаюсь нарисовать бесконечное количество фигур на холсте, поэтому я решил использовать прокрутку для этого. Однако, когда я добавляю вид прокрутки, ни одна из фигур не появляется на холсте.

пй:

# draws the shape
def draw_streak(self, obj):
    name = obj.id

    with open("streak.json", "r") as file:
        read = json.load(file)

    for key in read.keys():
        if key == name:
            with open("streak.json", "r+") as f:
                data = json.load(f)

            get_score = data.get(key, {}).get('score')

            can = self.root.get_screen("three")
            new_pos = can.pos
            for x in range(-1, get_score): # had to use -1 to get correct amount of shapes
                with can.ids.my_box.canvas:
                    Color(0, 1, 0, .75, mode='rgba')
                    rect = Rectangle(pos=new_pos, size=(30,30))
                new_pos[0] += rect.size[1]
                new_pos[0] += rect.size[0]

киловольт:

<ScreenThree>
    id: screen_three
    name: "three"
    on_leave: my_box.canvas.clear()
    on_leave: selected_streak.canvas.clear()
    on_leave: del_space.canvas.clear()

    GridLayout:
        cols: 1
        rows: 2
        GridLayout:
            cols: 3
            rows: 1
            AnchorLayout:
                anchor_x: "left"
                anchor_y: "top"
                Button:
                    text: "Back"
                    size: 50, 25
                    size_hint: None, None
                    font_size: 18
                    on_release: app.root.current = "two"
            AnchorLayout:
                id: selected_streak
                anchor_x: "center"
                anchor_y: "top"
            AnchorLayout:
                id: del_space
                anchor_x: "right"
                anchor_y: "top"
        ScrollView:
            do_scroll_x: False
            do_scroll_y: True
            GridLayout:
                cols: 1
                id: my_box
                size_hint_y: None
                height: self.minimum_height
                row_force_default: True
                row_default_height: 50

Кроме того, изменит ли подсказка размера x так, что фигуры, которые не подходят, будут перемещаться по экрану?

EDIT

Штриховка вызывается при нажатии кнопки в определенное время.

...
                elif delay > time.time() > self.honey:  # on time (green)
                    child.background_normal = ''
                    child.background_color = [0, 1, 0, .95]
                    child.unbind(on_press=self.early_click)
                    child.bind(on_press=self.add_score)
                    child.bind(on_press=self.display_streak)
                    child.bind(on_press=self.draw_streak)
                    child.unbind(on_press=self.late_click)

Ключ значения json score имеет то же имя, что и идентификатор кнопки.

EDIT

Скриншоты

PageTwo

PageThree

1 Ответ

1 голос
/ 06 июня 2019

Вопрос 3

Есть ли способ для моих прямоугольников сместиться вниз, когда они выходят из экрана, или когда они достигают определенного числа?

Решение

Нарисуйте прямоугольники слева направо и сверху вниз (lr-tb) ориентации.

Фрагменты

    root = App.get_running_app().root
    can = root.get_screen('three')
    new_pos = can.pos
    new_pos[1] = root.height - 60    # below the Back button

    for x in range(-1, get_score): # had to use -1 to get correct amount of shapes
        with can.canvas:
            Color(0, 1, 0, .75, mode='rgba')
            rect = Rectangle(pos=new_pos, size=(30,30))

        new_pos[0] += rect.size[0] * 2    # x co-ordinate
        if new_pos[0] >= (root.width - rect.size[0]):
            new_pos[0] = 0    # x co-ordinate
            new_pos[1] -= rect.size[0] * 2    # y co-ordinate

Вывод - Демо

Demot

Вопрос 2

хотел, чтобы фигура была нарисована на третьей странице, а не кнопка.

Решение

  • Заменить with can.ids.my_box.canvas: на with can.canvas:

Фрагменты

        can = App.get_running_app().root.get_screen('three')
        new_pos = can.pos
        for x in range(-1, get_score): # had to use -1 to get correct amount of shapes
            with can.canvas:
                Color(0, 1, 0, .75, mode='rgba')
                rect = Rectangle(pos=new_pos, size=(30,30))
            new_pos[0] += rect.size[1]
            new_pos[0] += rect.size[0]

Выход

Result - draw shapes on ScreenThree

Рисование фигур на кнопке в ScrollView

  • Реализация метода get_cell() для получения экземпляра кнопки внутри my_box

Фрагменты

    def get_cell(self, key):
        obj = App.get_running_app().root.get_screen('three')

        for row in reversed(obj.ids.my_box.children):
            if row.children:    # children is not empty
                for child in reversed(row.children):
                    if isinstance(child, Button):
                        if child.id == key:
                            return child
            elif isinstance(row, Button):
                if row.id == key:
                    return row
        return None

    def draw_streak(self, obj):
       ... 
            button = self.get_cell(key)    # get button instance
            if button:    # Not None
                new_pos = button.pos    # get button's position

                for x in range(-1, get_score):
                    with button.canvas:
                        Color(0, 1, 0, .75, mode='rgba')
                        rect = Rectangle(pos=new_pos, size=(30,30))
                    new_pos[1] += rect.size[1]    # y co-ordinate
                    new_pos[0] += rect.size[0]    # x co-ordinate

Выход

Demo

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...