Search code examples
pythonpython-3.xkivykivy-language

Problems with Kivy Screen Manager Python


I've been searching the internet for a fix, yet i can't seem to fix it..

I wanted to make a Game wherein of course there is a Menu and the Play Screens, But the Button are enormously big, despite of "size: 50, 50" and "pos: 300, 200"

main.py:

from kivy.app import App
from kivy.uix.widget import Widget
#from kivy.core.window import Window
#from kivy.properties import ObjectProperty
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.config import Config
from kivy.core.image import Image
from kivy.graphics import BorderImage
from kivy.graphics import Color, Rectangle
from kivy.uix.image import AsyncImage
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.screenmanager import ScreenManager, Screen, CardTransition
import time
import random
# Config.set('graphics', 'width', '1000')
# Config.set('graphics', 'height', '800')

class GridButtons(GridLayout):
    pass

class screen1(Screen):
    pass
    
class screen2(Screen):
    pass


class GameApp(App):
    
    def build(self):
        sm = ScreenManager()
        sm.add_widget(screen1(name='menu'))
        sm.add_widget(screen2(name='game'))
        return sm

        



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

kivy.kv

#kivy 2.0.0

<screen1>:
    orientation: 'vertical'
    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: 'gamebg.jpg'
            
    GridButtons:
        cols: 1
        rows: 1
        
        Button:
            size: 2, 2
            pos: 10, 20
            text: 'Play'

The screen i'm getting

I want the Play Button in the middle of the screen, and resizes automatically


Solution

  • If you want to set a widget of your desired size within a layout you have to disable the size_hint attr. Thus the change you need is,

            Button:
                size_hint: None, None
                size: 2, 2
    

    I want the Play Button in the middle of the screen..

    Since you are adding Button directly within GridLayout and it manages its children's position automatically (by default lr-tb meaning left to right, top to bottom; from version 2.0.0), none of pos or pos_hint will work as intended.

    To achieve this you may add it within a FloatLayout as,

        FloatLayout:
    
            Button:
                size_hint: None, None
                size: 2, 2
                pos_hint: {"center_x" : 0.5, "center_y" : 0.5}