首页 > 解决方案 > 如何从 Kivy 弹出窗口中完全删除标题(使用 Python 而不是 .kv)?

问题描述

我想创建一个 Kivy 弹出窗口,在左上角有一个“x”按钮来关闭弹出窗口。我创建了按钮和这个功能,它在左上角但不是最左上角

在此处查看弹出窗口的图像

我遇到了Popup.title. 似乎 title_size 仅更改标题中文本的字体大小,而不是标题本身。您是否知道更改标题的方法,以便我的按钮可以位于最左上角?

import sys
import time
from kivy.app import App
from kivy.graphics import Color, Rectangle
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.relativelayout import RelativeLayout #for popup 'x' button
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.uix.label import Label


class RootWidget(BoxLayout):

    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)

        self.inside = BoxLayout(spacing = 10)
        self.add_widget(self.inside)

        self.btn2 = Button(text="Open popup", size_hint=(.5, .3))

        self.btn2.bind(on_press=self.workscreen)
        self.add_widget(self.btn2)

        content = RelativeLayout()
        content_cancel = Button(text='x', 
                        pos_hint={'left': 1, 'top': 1}, 
                        size_hint=(.1, .1),
                        background_normal='',
                        background_color=(0, 0.4, 1, 1))
        content.add_widget(content_cancel)
        content.add_widget(Label(text="This is some helpful text."))
        self.popup = Popup(title='', separator_height=0,
                    #content=Button(text='Close me!', pos_hint={'left': 1, 'top': 1}),
                    title_size=0, 
                    content=content,
                    auto_dismiss=False,
                    size_hint=(None, None), size=(400, 400))

        content_cancel.bind(on_press=self.popup.dismiss) #for popup 'x' button

    def workscreen(self, instance):
        self.popup.open()


class MainApp(App):

    def build(self):

        self.root = root = RootWidget()
        root.bind(size=self._update_rect, pos=self._update_rect)

        with root.canvas.before:
            self.rect = Rectangle(size=root.size, pos=root.pos)
        return root

    def _update_rect(self, instance, value):
        self.rect.pos = instance.pos
        self.rect.size = instance.size


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

标签: pythonkivy

解决方案


在您的__init__()方法中,您可以添加:

    title_label = self.popup.children[0].children[2]
    title_label.height = 0

就在创建Popup. 这是一个非常丑陋的 hack,如果Popup类被Kivy更新更改,可能会失败。


推荐阅读