为什么kivy窗口自动比指定的大25%?

问题描述 投票:0回答:2

我正在用 kivy 创建一个游戏,发现窗口大小总是比我指定的大 25%:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.window import Window

# screen dimensions, px
screen_width = 400
screen_height = 600
Window.size = (screen_width, screen_height)

class PlayGame(Widget):
    def on_touch_move(self, touch):
        self.touch = touch
        print(self.touch.x, self.touch.y)


class TestGame(App):
    def build(self):
        return PlayGame()


if __name__ == '__main__':
    game = TestGame()
    game.run()

运行此代码,然后单击鼠标并沿着屏幕一侧运行它会得到 500 的宽度,沿着顶部执行相同的操作会得到 750 的高度。

我查看了 kivy 文档,但它仅提供窗口大小

Get the rotated size of the window. If rotation is set, then the size will change to reflect the rotation.

New in version 1.0.9.

size is an AliasProperty.

我不确定这些是否有帮助,特别是考虑到窗口没有旋转。

python kivy window
2个回答
0
投票

当你改变一个

Window.size
时,kivy会触发一些函数来更新窗口大小。 kivy 中的这部分代码是您问题背后的原因。

文件

..\Python\Python39\site-packages\kivy\core\window\__init__.py", line 420

    def _get_size(self):
        r = self._rotation
        w, h = self._size
        if platform == 'win' or self._density != 1:
            w, h = self._win._get_gl_size()
        if self.softinput_mode == 'resize':
            h -= self.keyboard_height
        if r in (0, 180):
            return w, h
        return h, w

如果您的系统是基于Windows的,则窗口大小可以通过此功能更改

self._win._get_gl_size()
。除非您编辑 kivy 代码或平台值,否则您无法阻止它更改它,这是不建议并且可能会导致严重问题。

一种解决方案是找到比例并将其乘以 x 和 y 值。

screen_width = 400
screen_height = 600
Window.size = (screen_width, screen_height)
scale = Window._size[0] / Window.size[0]
print(Window._size, Window.size, scale)

class PlayGame(Widget):
    def on_touch_move(self, touch):
        self.touch = touch
        print(self.touch.x * scale, self.touch.y * scale)

-1
投票

您遇到的 Kivy 窗口尺寸大于您指定的尺寸的问题可以归因于某些系统上默认应用的 DPI(每英寸点数)缩放因子。 Kivy 根据 DPI 缩放自动调整窗口大小,以确保在不同屏幕密度的不同设备上呈现一致的渲染。

要解决此问题并使窗口大小准确匹配您指定的尺寸,您可以通过修改代码来禁用 Kivy 中的 DPI 缩放,如下所示:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.window import Window

screen_width = 400
screen_height = 600

class PlayGame(Widget):
    def on_touch_move(self, touch):
        self.touch = touch
        print(self.touch.x, self.touch.y)


class TestGame(App):
    def build(self):
        Window.size = (screen_width, screen_height)
        return PlayGame()


if __name__ == '__main__':
    game = TestGame()
    game.run()

通过将 Window.size 赋值移到 TestGame 应用程序类的 build() 方法中,将在构建应用程序之前设置窗口大小。这可确保正确应用指定的尺寸,而无需 DPI 缩放。

通过此修改,Kivy 窗口应准确匹配您指定的尺寸(400x600 像素)。

© www.soinside.com 2019 - 2024. All rights reserved.