gpt4 book ai didi

python - 更改背景 Canvas kivy

转载 作者:太空宇宙 更新时间:2023-11-03 20:31:07 26 4
gpt4 key购买 nike

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

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()

最佳答案

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

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 会自动为您设置的操作,但必须进行设置手动,因为矩形不是在kv中创建的。

关于python - 更改背景 Canvas kivy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57503195/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com