简体   繁体   中英

Kivy: How do I use layouts within seperate screens while using ScreenManager?

I have some Kivy code which so far displays a Screen (BrickBreakerMenuScreen) with an Image and a Label, which, when pressed, changes to a blank Screen (GameScreen) with an image in the centre. However, this is not the aim of my code; as you can see from the Builder, the second screen should align the Image in the top right corner:

from kivy.lang import Builder
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.image import Image
from kivy import Config
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.uix.widget import Widget
from kivy.animation import Animation
import time

Config.set('graphics', 'multisamples', '0')
Builder.load_string('''
<BrickBreakerMenuScreen>:
    BoxLayout:
        orientation: 'vertical'
        Image:
            source: 'brickbreaker log.png'
        Label:
            font_name: 'vgafix.fon'
            text: 'Tap to start'

<GameScreen>:
    AnchorLayout:
        anchor_x: 'right'
        anchor_y: 'top'
        Image:
            source: 'settings-cog.png'
''')

class BrickBreakerMenuScreen(Screen):
    def __init__(self, **kwargs):
        super(BrickBreakerMenuScreen, self).__init__(**kwargs)

    def on_touch_down(self, touch):
        sm.current = 'game'

class GameScreen(Screen):
    def __init__(self, **kwargs):
        super(GameScreen, self).__init__(**kwargs)

sm = ScreenManager(transition = FadeTransition())
sm.add_widget(BrickBreakerMenuScreen(name='menu'))
sm.add_widget(GameScreen(name='game'))

class BrickBreakerInsanityApp(App):
    def build(self):
        return sm



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

Is this a problem due to the ScreenManager? I have changed the kv script to attempt to see if it's an issue with AnchorLayout, but none of the other layouts change the image's location on the GameScreen.

Any help is much appreciated. Thanks!

Images:

来自GameScreen的齿轮

来自BrickBreakerMenuScreen的徽标

Your code is working OK. The image is at the top-right corner.
Your problem is the size of that Image widget. Its as big as the size of the window.
To fix this, you could add size_hint: .1, .1 to the Image properties and it will display as you want.

    Image:
        size_hint: .1, .1
        source: 'settings-cog.png'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM