sotrh
sotrh

Reputation: 43

Kivy: Code Popup Dismiss Button in KV Language

I'm trying to code a custom popup in kivy for picking a color from the ColorPicker widget. Right now i'm trying to hook up an 'OK' button to dismiss the popup, but it's not working. The popup up displays correctly, but when i click OK, nothing happens. The popup continues on screen.

Here's my python code.

from kivy.app import App
from kivy.uix.popup import Popup
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.colorpicker import ColorPicker

class PaintWindow(BoxLayout):
    pass

class CPopup(Popup):
    def on_press_dismiss(self, *args):
        self.dismiss()
        return False

class PixPaint(App):
    def build(self):
        pw = PaintWindow()
        return pw

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

Here's the KV code.

<PaintWindow>:
    orientation: 'vertical'
    CPopup:

<CPopup>:
    title: 'Pick a Color'
    size_hint: 1.0, 0.6
    id: cpopup

    BoxLayout:
        orientation: 'vertical'

        ColorPicker:
            size_hint: 1.0, 1.0

        Button:
            text: 'OK'
            size_hint: 1.0, 0.2
            on_press: cpopup.on_press_dismiss()

Any help is much appreciated. Sorry for all the code! :)

Upvotes: 4

Views: 4596

Answers (1)

toto_tico
toto_tico

Reputation: 19027

The reason the popup is not closing is because you are adding it directly to your PaintWindow here:

<PaintWindow>:
    orientation: 'vertical'
    CPopup:

Instead of actually calling the method open() of Popup. So,

1 - Remove the CPopup: from the kv file

<PaintWindow>:
    orientation: 'vertical'
    #CPopup:
 ...

2 - Call the open() method somewhere else. As a good example in the build(self) of PixPaint

class PixPaint(App):
    def build(self):
        pw = PaintWindow()
        popup = CPopup();
        popup.open()
        return pw

Just in case, a few extras:

  1. You can also get rid off the id: cpopup on the the definition of <CPopup>: and use root instead (on_press: root.on_press_dismiss()).
  2. Moreover, you can get rid off the on_press_dismiss() and do on_press: root.dismiss() instead.

Upvotes: 5

Related Questions