首页 > 解决方案 > 为什么 kivy 的小部件的大小不是真实的?

问题描述

有我的代码:

class MyGame(Widget):
    def prepare_game(self):
        print(self.height, self.width)

class MyApp(App):
    def build(self):
        game = MyGame()
        game.prepare_game()
        return game

MyApp().run()

输出是 100 100,但事实并非如此。当我想调用方法 prepare_game() 一次时,我可以找出小部件的实际大小吗?

标签: pythonkivy

解决方案


这是因为在您上面的示例中,未设置小部件的大小。在这种情况下,您将获得默认大小,即 100、100。更新后的大小始终可以通过on_size以下示例中所示的方法找到。

from kivy.app import App
from kivy.uix.widget import Widget

class MyGame(Widget):        
    def prepare_game(self):
        print(self.height, self.width)

    def on_size(self, *args):
        print(self.size)

class MyApp(App):
    def build(self):
        game = MyGame()
        game.prepare_game()
        return game

MyApp().run()

推荐阅读