Search code examples
python-3.xkivykivy-language

Get window size in Kivy not from the main class using kv file


I'm trying to define in a .kv file the size of a custom button, referring to the size of the window of the App. Since the custom button class (<CustomButton @ Button>:) is different from the main class ( :) returned by the build method, I cannot use size: (root.width, root.height). I then tried to define an id for the main class and use it in the CustomButton class as size: (main_class_id.width, main_class_id.height), to use size: (Factory.MyMainClass (). Width, Factory.MyMainClass (). Height) , to use size: app.width, app.height but nothing seems to work. Do you have any suggestions for getting what I want without using BoxLayout or anything else?

Following, I paste the py and kv files.

Thanks in advance for your answers.

py file:

from kivy.config import Config
Config.set('graphics', 'resizable', '0')

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

Window.size = (320, 365)
Window.minimum_width, Window.minimum_height = Window.size
Window.clearcolor = (.95, .95, .95, 1)

Builder.load_file('exercise_1.kv')

class MyMainClass(Widget):
    pass

class MyApp(App):
    def build(self):
        return MyMainClass()

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

kv file:

#:import Factory kivy.factory.Factory

<MyMainClass>:
    id: main_class_id

    Label:
        id: display_label
        text: '0'
        size: root.width*0.95, root.height*0.23
        pos: (root.width*0.5 - self.width*0.5), (root.height - self.height)
        font_name: 'fonts/Lcd.ttf'
        font_size: '48dp'
        color: 0, 0, 0, 1
        text_size: self.size
        halign: 'right'
        valign: 'middle'

    CustomButton:
        text: '1'
        #size: root.width*0.2, root.height*0.1

<CustomButton@Button>:
    background_color: 'red'
    size: main_class_id.width*0.2, main_class_id.height*0.1 #Not workings
    size: app.width*0.2, app.height*0.1 #Not workings
    size: Factory.MyMainClass().width*0.2, Factory.MyMainClass().height*0.1 #Not workings

Solution

  • I found the solution:

    The solution was to add the following attributes in the build method of the MyApp class:

    class MyApp(App):
        def build(self):
            self.width = Window.width
            self.height = Window.height
            return MyMainClass()
    

    Then use these two attributes in the kv file as follows:

    <CustomButton@Button>:
        size: app.width*0.2, app.height*0.1
    

    I hope this information will be useful.

    *This solution works only if you disable the resize