【问题标题】:Popup widget doesn't reopen in Kivy弹出小部件不会在 Kivy 中重新打开
【发布时间】:2020-08-19 04:51:46
【问题描述】:

当按下一个键时,弹出窗口通过按下按钮打开,它关闭,但是当再次按下该键时,调用弹出窗口会出错

WidgetException('不能添加 %r,它已经有一个父 %r'

import json
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.popup import Popup


def read_json(file):
    FileJson = open(file)
    ObjJsom = json.load(FileJson)
    return ObjJsom


data = read_json('Task.json')

counter = 0
task_Headline = data['Tasks'][counter]['Headline']
label = Label(text="Label test for StackoverFlow")
ConBox = BoxLayout(orientation="vertical")
clButt = Button(text="Close", size_hint=(1, 0.1))
ConBox.add_widget(label)
ConBox.add_widget(clButt)


def btn(instance):
    show_popup(ConBox)


def show_popup(conten):
    show = conten
    popupWindow = Popup(title="Popup Window", content=show)
    clButt.bind(on_press=popupWindow.dismiss)
    popupWindow.open()


class Test(App):
    def build(self):
        butt = Button(text='Press')
        butt.bind(on_press=btn)
        return butt


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

【问题讨论】:

    标签: python python-3.x kivy


    【解决方案1】:

    当您创建 Popup 时:

    popupWindow = Popup(title="Popup Window", content=show)
    

    它将show 添加到Popup 实例。这设置了showparent 属性。当Popup 被解除并使用上面的行创建一个新的Popup 时,它会失败,因为show 实例仍然认为它的父级是旧的Popup(即使它已被解除)。并且任何小部件只能有一个父级。修复方法是从旧的 Popup 中删除 show 实例,如下所示:

    def show_popup(conten):
        # make sure the content has no parent
        if conten.parent is not None:
            conten.parent.remove_widget(conten)
        show = conten
        popupWindow = Popup(title="Popup Window", content=show)
        clButt.bind(on_press=popupWindow.dismiss)
        popupWindow.open()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      • 2022-01-15
      • 2018-09-23
      • 1970-01-01
      相关资源
      最近更新 更多