【问题标题】:change the background canvas kivy更改背景画布 kivy
【发布时间】:2019-12-21 12:18:22
【问题描述】:

我有一个画布背景,但是当有人使用正确的按钮进入下一个级别时,我正在尝试切换背景。我正试图在一堂课内完成这一切。有没有办法将图像分配给画布矩形,然后按下按钮,画布图像将更改为新来源。

main.py

class MazeSolution(Screen):
    def CheckDoor1(self):
        if self.ids.door1.source == "correct":
            print("correct")
            self.ids.change.source = 's-curvee selection.png'
        else:
            print("incorrect")

main.kv

#:import utils kivy.utils
<MazeSolution>:
    FloatLayout:
        canvas:
            Rectangle:
                id: change
                source: 'selection grass.png'
                pos: self.pos
                size: self.size
        Button:
            pos_hint: {"top": .8, "right": .75}
            size_hint: .5, .1
            text:
                "Door 1"
            source: "<random_name>"
            id: door1
            on_press:
                root.CheckDoor1()

【问题讨论】:

标签: python image canvas kivy


【解决方案1】:

我认为不支持在 canvas 指令中分配 ids。但是你可以通过在python 中创建Rectangle 来完成同样的事情:

from kivy.app import App
from kivy.graphics.vertex_instructions import Rectangle
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager


class MazeSolution(Screen):
    def __init__(self):
        super(MazeSolution, self).__init__()
        # make the Rectangle here and save a reference to it
        with self.canvas.before:
            self.rect = Rectangle(source='selection grass.png')

    def on_pos(self, *args):
        # update Rectangle position when MazeSolution position changes
        self.rect.pos = self.pos

    def on_size(self, *args):
        # update Rectangle size when MazeSolution size changes
        self.rect.size = self.size

    def CheckDoor1(self):
        if self.ids.door1.source == "correct":
            print("correct")
            # use the saved reference to change the background 
            self.rect.source = 's-curvee selection.png'
        else:
            print("incorrect")

Builder.load_string('''
<MazeSolution>:
    FloatLayout:
        Button:
            pos_hint: {"top": .8, "right": .75}
            size_hint: .5, .1
            text:
                "Door 1"
            source: "correct"
            id: door1
            on_press:
                root.CheckDoor1()
''')

class TestApp(App):
    def build(self):
        sm = ScreenManager()
        sm.add_widget(MazeSolution())
        return sm

TestApp().run()

on_pos()on_size() 方法执行kv 会自动为您设置的操作,但必须手动设置,因为Rectangle 不是在kv 中创建的。

【讨论】:

    猜你喜欢
    • 2014-03-01
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    相关资源
    最近更新 更多