user15069371
user15069371

Reputation:

How can I put the button to center of the window using Kivy library?

I am writing a mobile game in python through the Kivy library and i'm faced to problem. I want to put the button to center of the window, but whatever parameters I gave, it is still stayed in the lower left corner. I tried to using 'pos: ' instead of 'pos_hint: ', but I can't move it in anyway. Please help to solve this problem.(see screenshot).

.py file:

from kivy.app import App 
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.config import Config


Config.set('graphics', 'resizable', '0')
Config.set('graphics', 'width', '1280')
Config.set('graphics', 'height', '720')


class HangApp(App):
    def build(self):
        return background()
    

class background(Widget):
    pass    


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

.kv file:

<background>
    canvas:
        Rectangle:
            source: 'background.png'
            size: self.size
            pos: self.pos

    Button:
        text: "press"
        size_hint: 0.3, 0.3
        pos_hint: {"x":.5, "top":.5}

Upvotes: 0

Views: 54

Answers (1)

John Anderson
John Anderson

Reputation: 38822

Your background class is a simple Widget, which does not honor the pos_hint attributes of its children. Those type of attributes are used by the Layout classes. Try changing:

class background(Widget):
    pass    

to:

class background(FloatLayout):
    pass

Upvotes: 1

Related Questions