Изменить всплывающий текст в Kivy - PullRequest
0 голосов
/ 21 мая 2018

Я новичок в Kivy, так что это может быть тривиальным вопросом.Я работаю над проектом, который имеет два экрана, каждый из которых содержит кнопку, которая генерирует всплывающее окно.Я бы хотел, чтобы во всплывающем окне отображался оператор, содержащий имя текущего экрана.Моя проблема, несмотря на наличие метода для изменения всплывающего текста, текст заполнителя всегда отображается.Почему метод changeText не изменяет текст всплывающего окна?

Моя проблема похожа на показанную ниже:

Однако у меня возникли некоторые проблемы с пониманием того, как применить его в моей конкретной ситуации.

Код Python:

class Screen1(Screen):  
    pass

class Screen2(Screen):
    pass 

class MyManager(ScreenManager):
    pass

class PopUp(Popup):
    def changeText(self,nameStr):
        self.ids.label.text = "You are on Screen %s!" %nameStr #this is text that I want to display 

class PrimaryApp(App):
    def build(self):
        return MyManager()

PrimaryApp().run()

Код Kv:

#:import Factory kivy.factory.Factory
<MyManager>:
    Screen1:
        id: screen1
    Screen2: 
        id: screen2

<Screen1>:
    name: "one"
    GridLayout:
        id: grid
        rows: 2
        Button:
            id: button1
            text: "Go to Screen Two"
            on_release: root.manager.current = "two" 
        Button: 
            id: button2
            text: "Display Popup" 
            on_release: 
                Factory.PopUp().changeText(root.name)
                Factory.PopUp().open()
<Screen2>: 
    name: "two" 
    GridLayout:
        id: grid
        rows: 2 
        Button:
            id: button1
            text: "Go to Screen One" 
            on_release: root.manager.current = "one" 
        Button: 
            id: button2
            text: "Display Popup"
            on_release:
                Factory.PopUp().changeText(root.name)
                Factory.PopUp().open()


<PopUp>:
    id:pop
    size_hint: (.5,.5)
    title: "Notice!" 
    Label: 
        id: label
        text: "PLACEHOLDER TEXT" #this is not the code I want displayed

[1]:

Ответы [ 2 ]

0 голосов
/ 22 мая 2018

Используйте событие Popup, on_open , чтобы изменить содержимое всплывающего окна, текст виджета Label.

Popup »API

События:on_open:
Запускается при открытии всплывающего окна.

Фрагменты

<PopUp>:
    on_open:
        label.text = "You are on Screen %s!" % app.root.current
    id:pop
    ...

Пример

main.py

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.popup import Popup


class Screen1(Screen):
    pass


class Screen2(Screen):
    pass


class MyManager(ScreenManager):
    pass


class PopUp(Popup):
    pass


class PrimaryApp(App):
    def build(self):
        return MyManager()


PrimaryApp().run()

primary.kv

#:kivy 1.10.0
#:import Factory kivy.factory.Factory

<MyManager>:
    Screen1:
        id: screen1
    Screen2:
        id: screen2

<Screen1>:
    name: "one"
    GridLayout:
        id: grid
        rows: 2
        Button:
            id: button1
            text: "Go to Screen Two"
            on_release: root.manager.current = "two"
        Button:
            id: button2
            text: "Display Popup"
            on_release:
                Factory.PopUp().open()
<Screen2>:
    name: "two"
    GridLayout:
        id: grid
        rows: 2
        Button:
            id: button1
            text: "Go to Screen One"
            on_release: root.manager.current = "one"
        Button:
            id: button2
            text: "Display Popup"
            on_release:
                Factory.PopUp().open()


<PopUp>:
    on_open:
        label.text = "You are on Screen %s!" % app.root.current
    id:pop
    size_hint: (.5,.5)
    title: "Notice!"
    Label:
        id: label
        text: "PLACEHOLDER TEXT" #this is not the code I want displayed

Выход

Img01 - Popup at Screen 1 Img02 - Popup at Screen 2

0 голосов
/ 21 мая 2018

каждый раз, когда вы звоните Factory().Popup(), создается новый Popup, который не имеет ничего общего с предыдущим.Что вы можете сделать, это:

в кв:

...
<Screen1>:
    name: "one"
    GridLayout:
        id: grid
        rows: 2
        Button:
            id: button1
            text: "Go to Screen Two"
            on_release: root.manager.current = "two"
        Button:
            id: button2
            text: "Display Popup"
            on_release:
                p = Factory.PopUp()
                p.changeText(root.name)
                p.open()

И то же самое для второго экрана.Но каждый раз, когда вы отпускаете эти кнопки, создается новое всплывающее окно, слишком много памяти тратится.Лучшее, что вы можете сделать, это инициализировать ваш менеджер экрана с помощью всплывающего окна, а затем изменить только текст этого всплывающего окна:

Python:

...
from kivy.properties import ObjectProperty

...
class PopUp(Popup):
    def changeText(self,*args):
        self.ids.label.text = "You are on Screen %s!" % args[0].current

class MyManager(ScreenManager):
    popup = ObjectProperty()

    def __init__(self, **kwargs):
        super(MyManager, self).__init__(**kwargs)
        self.popup = PopUp()
        self.bind(current=self.popup.changeText)

и kv:

...
<PopUp>:
    id:pop
    size_hint: (.5,.5)
    title: "Notice!"
    Label:
        id: label
        text: "You are on Screen one!"

<Screen1>:
    name: "one"
    GridLayout:
        id: grid
        rows: 2
        Button:
            id: button1
            text: "Go to Screen Two"
            on_release: root.manager.current = "two"
        Button:
            id: button2
            text: "Display Popup"
            on_release:
                root.manager.popup.open() #Same thing for the second screen
...