【问题标题】:Kivy places widgets slightly differently through Python and Kivy language. Am I missing something?Kivy 通过 Python 和 Kivy 语言放置小部件的位置略有不同。我错过了什么吗?
【发布时间】:2016-12-27 13:46:47
【问题描述】:

我刚拿起Kivy,就遇到了这个问题。不过,如果有更好的方法来实现我的总体目标,我很乐意听到。

我注意到,当我将一个小部件添加到另一个小部件时,如果我通过 Python 代码执行此操作,它的位置将与我通过 Kivy 执行的操作略有不同。我将在下面粘贴我的代码(现在很短),您可以自己尝试一下,您就会明白我的意思。

client.py:

import kivy
kivy.require('1.9.1') # current kivy version

from kivy.config import Config
Config.set('graphics', 'width', '360')
Config.set('graphics', 'height', '640')

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty, NumericProperty, ReferenceListProperty
from kivy.graphics import Color, Rectangle
from kivy.clock import Clock
from kivy.vector import Vector
from random import randint

class Bird(Widget):
    '''
        Bird Widget defines each sprite. / Test version: blue and red cards
        Defined attributes:
            SIZE
            POSITION
            (COLOR)
        Upade the position of this widget individually every 0.7 seconds with 60 fps
    '''

    # set attributes
    border_color = (1,1,1)
    r = NumericProperty(0)
    g = NumericProperty(0)
    b = NumericProperty(0)
    color = ReferenceListProperty(r, g, b) # initial color = red // maybe make it random

    velocity_x = NumericProperty(0)
    velocity_y = NumericProperty(-3)
    velocity = ReferenceListProperty(velocity_x, velocity_y)

    def __init__(self, **kwargs):
        super(Bird, self).__init__(**kwargs)
        self.pick_color()

    # Randomly generate 0 or 1, and pick a color based on that
    def pick_color(self):
        color_num = randint(0,1)

        if color_num == 0: # blue
            self.color = (0,0,1)
        elif color_num == 1: # red
            self.color = (1,0,0)

    # Move the widget by -3y increment at 60 fps
    def increment(self, dt):
        self.pos = Vector(*self.velocity) + self.pos

    def move(self):

        # While the sprite moves at 60 fps, the movement is "cancelled" after 0.3 seconds
        # This event sequence is refreshed every 0.7 seoncds in MainApp class
        move = Clock.schedule_interval(self.increment, 1.0/60.0)
        stop = Clock.schedule_once(lambda dt: move.cancel(), 0.3)


class GameMain(Widget):
    '''
        Contains two functions: ADD_NEW_BIRD() and UPDATE().
        All controls happen in this widget
        Not using kivy.screen because there is only one screen used

        ADD_NEW_BIRD() adds a new bird to list_of_birds AND add it as a child widget to the GameMain Widget. UPDATE() calls MOVE() (Bird Widget) and receives events

        Create global variable limit = 0; if limit == 4, game over; variable accessed in update function, which checks whether the limit has been reached. If the player makes the right decision, then limit -= 1
    '''

    limit = 0

    def add_new_bird(self):
        self.new_bird = Bird(center_x=self.center_x, center_y=self.height/1.5)
        print (self.center_x, self.height)
        self.new_bird.pick_color()
        self.add_widget(self.new_bird)

    def update(self, dt):
        for bird in self.children:
            bird.move()

        self.add_new_bird()

class MainApp(App):

    def build(self):    
        game = GameMain()
        Clock.schedule_interval(game.update, 0.7)
        return game


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

main.kv:

#:kivy 1.9

<Bird>:
    size: 70, 80
    canvas:
        Color:
            rgb: self.border_color
        Rectangle:
            size: self.size
            pos: self.pos
        Color:
            rgb: self.color
        Rectangle:
            size: root.width - 10, root.height - 10
            pos: root.x + 5, root.y + 5

<GameMain>
    Bird:
        center_x: root.center_x
        center_y: root.height / 1.5

代码完全符合我的要求(稍后我将介绍 z 值),只是第一张卡片稍微偏向左侧。我真的很困惑,因为据我所知,main.kv 中的center_x: root.center_x 与client.py 中的Bird(center_x=self.center_x 应该没有什么不同。我尝试在 init 函数中初始化 Bird() 的第一个实例,如下所示:

def __init__(self, **kwargs):
    super(GameMain, self).__init__(**kwargs)
    self.bird = Bird(center_x=self.center_x, center_y=self.height/1.5)
    self.bird.pick_color()
    self.add_widget(self.bird)

问题仍然存在!如果有人能解释发生了什么/我做错了什么,甚至可以提出更好的方法来解决这个问题,我将不胜感激。

以防万一您好奇,我需要直接从 Python 代码添加小部件,因为我需要应用程序以恒定的时间间隔不断地生成一张新卡片。然而,为了简单起见,第一张卡在 Kivy 文件中进行了初始化。公平地说,它工作得很好,除了偏移量。最后,我没有使用 Layout,因为我不确定要使用哪一个……我确实在 FloatLayout 上放了一段时间,但它似乎并不能解决我的问题。

【问题讨论】:

    标签: python kivy


    【解决方案1】:

    在构造时,Widget 的初始大小为 (100, 100)。如果您从此更改大小:

    <Bird>:
        size: 70, 80
    

    到这里:

    <Bird>:
        size: 100, 80
    

    矩形将正确对齐。在 kv 文件中创建的初始矩形以父窗口为中心,在 Python 代码中创建的其他矩形向左偏移。

    如果您在 Python 代码中更改 Bird 构造函数:

    def __init__(self, **kwargs):
        super(Bird, self).__init__(**kwargs)
        self.pick_color()
    

    到此(有效地将默认小部件尺寸从 (100, 100) 覆盖为 (50,50)):

    def __init__(self, **kwargs):
        self.size = (50, 50)
        super(Bird, self).__init__(**kwargs)
        self.pick_color()
    

    您会注意到在 Python 代码中创建的矩形将向右移动。更改 kv 文件:

    <Bird>:
        size: 70, 80
    

    到:

    <Bird>:
        size: 50, 80
    

    与宽度为 (50,50) 的(新)初始小部件尺寸匹配,所有矩形将再次对齐。

    您的问题的解决方案是保持原样,除了将 Python 中的新鸟的 size 设置为与 kv 文件中的相同:

    def __init__(self, **kwargs):
        self.size = (70, 80)
        super(Bird, self).__init__(**kwargs)
        self.pick_color()
    

    一切都会按预期工作。

    这一切都意味着 kv 文件中的size 属性不适用于您在 Python 端创建的 Birds,仅适用于由 kv 声明创建的 Birds。这是 Kivy 的错误,还是您在 Python 代码中错过了让 Builder 将 kv 文件中的 size 应用到 Python 创建的 Birds 的更多步骤,我现在不知道。

    根据我的经验,在 Kivy 开发的这一点上,混合过多的 kv 和 Python 代码会导致您在这里遇到这些奇怪的问题。最好要么在 kv 中处理所有与视图相关的东西,要么完全放弃 kv 并在 Python 中构建所有内容。

    有些东西在 kv 中根本不起作用,即设置 GridLayout (v1.9.1) 的 cols 属性。

    就个人而言,目前,我坚持使用组织良好的 Python 代码来构建 UI,几乎完全不使用 kv 文件。

    希望这会有所帮助...

    【讨论】:

    • 谢谢。我最终使用了一种解决方法,但知道这会让我头疼不已。还有关于不要混合太多 kivy 和 python 的部分——我现在看到这个问题,与 Popups。我很想拥有那种理想的“分离”(kivy 处理所有 UI 的东西,python 处理逻辑),但由于我经常动态添加小部件,所以我最终会更多地使用 python。也许我应该完全放弃 kivy 文件..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多