Kivy Popup 更改背景

Kivy Popup change background

我不确定为什么,但是当我想更改我的弹出背景(我在 python 中创建,而不是 kivy)时,我更改了整个屏幕的背景,除了我的实际弹出窗口。我的代码看起来像这样(分解了很多):

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.core.window import Window

class BoxL(BoxLayout):
    def chooseFile(self):
        self.chosePop = Popup()
        self.chosePop.title = 'My Popup'
        choseBox = BoxLayout()
        choseBoxLabel = Label()
        choseBoxLabel.text = 'Any Text'
        choseBox.add_widget(choseBoxLabel)
        self.chosePop.content = choseBox
        self.chosePop.background_normal = ''
        self.chosePop.background_color = 0.5, 0.75, 0, 0.75
        self.chosePop.open()

class GUI(App):
    def build(self):
        self.title = 'MyApp'
        return BoxL()

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

我也尝试过的是:

from kivy.graphics import Rectangle, Color

class BoxL(BoxLayout):
    def chooseFile(self):
        with self.chosePop.canvas:
             Color(0, 0.5, 0.75, 0.75)
             Rectangle(pos=choseBox.pos, size=choseBox.size)
             #Rectangle(pos=self.chosePop.pos, size=self.chosePop.size) #this brings the correct size but at a wrong position, and the original popup background doesnt get changed either)

在您的 Popup 中,您看到的大部分是 Labels 的背景。一个 Labeltitle,另一个是你的 ChooseBoxLabel。您可以轻松调整 ChooseBoxLabel 的背景颜色,方法是使用带有 kv 规则的自定义 class 为背景创建彩色 Rectangletitle Label 更难,因为 Popup 的开发者没有任何方法访问 title 背景颜色。

以下是您可以执行的一些操作的示例:

from kivy.app import App
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from kivy.uix.label import Label

class MyBoxLayout(BoxLayout):
    pass

Builder.load_string('''
<Label>:  # Note that this affects EVERY Label in the app
    canvas.before:
        Color:
            rgba: 1,0,0,1
        Rectangle:
            pos: self.pos
            size: self.size
<MyBoxLayout>:
    canvas.before:
        Color:
            rgba: 0,0,1,1
        Rectangle:
            pos: self.pos
            size: self.size
''')

class BoxL(BoxLayout):
    def chooseFile(self):
        self.chosePop = Popup()
        self.chosePop.title = 'My Popup'
        choseBox = MyBoxLayout()
        choseBoxLabel = Label()
        choseBoxLabel.size_hint_y = 0.2
        choseBoxLabel.text = 'Any Text'
        choseBox.add_widget(choseBoxLabel)
        self.chosePop.content = choseBox
        self.chosePop.size_hint = (.5, .5)
        self.chosePop.open()

class GUI(App):
    def build(self):
        self.title = 'MyApp'
        Clock.schedule_once(self.do_popup, 3)
        return BoxL()

    def do_popup(self, dt):
        self.root.chooseFile()

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

在上面的代码中,MyBoxLayout 自定义 class 提供了蓝色背景,只有当其中的 Label 没有填充 Layout 时才可见。 kv 中的 Label 规则为 titlechooseBoxLabel 提供了背景颜色,但它会影响 App 中的每个 Label .

其实我觉得这个很简单。我的回答使问题复杂化。我相信您只需要添加以下行:

self.chosePop.opacity = 0.5

在您创建 Popup.

之后