Last active
July 20, 2023 02:27
-
-
Save pjz/6a8c8e03b6b610c4b4e202a9115b5ad7 to your computer and use it in GitHub Desktop.
Wrapper for simple dialog/prompt using kivy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from kivy.logger import Logger | |
from kivymd.app import MDApp | |
from kivymd.uix.screen import MDScreen | |
from kivymd.uix.button import MDFlatButton | |
from kivymd.uix.boxlayout import MDBoxLayout | |
from kivymd.uix.dialog.dialog import MDDialog | |
from kivymd.uix.textfield.textfield import MDTextField | |
class AskDialog: | |
def __init__(self, title, callback, hint): | |
self._callback = callback | |
hint_text = hint or "" | |
self._dialog_text = MDTextField(hint_text=hint_text) | |
self.dialog = MDDialog( | |
title=title, | |
type="custom", | |
pos_hint={"center_x": .5, "center_y": .5}, | |
buttons=[ | |
MDFlatButton(text="Cancel", on_release=lambda x: self.pressed_cancel(x)), | |
MDFlatButton(text="OK", on_release=lambda x: self.pressed_ok(x)) | |
], | |
content_cls=MDBoxLayout( | |
self._dialog_text, | |
orientation="vertical", | |
spacing="12dp", | |
size_hint_y=None, | |
height="120dp", | |
) | |
) | |
def launch(self): | |
self.dialog.open() | |
def pressed_cancel(self, buttonid): | |
Logger.info("pressed cancel") | |
self.dialog.dismiss() | |
def pressed_ok(self, buttonid): | |
Logger.info("pressed ok") | |
self._callback(self._dialog_text.text) | |
self.dialog.dismiss() | |
@classmethod | |
def ask(cls, prompt, callback, hint=None): | |
dialog = cls(title=prompt, callback=callback, hint=hint) | |
dialog.launch() | |
class TestApp(MDApp): | |
def build(self): | |
self.theme_cls.theme_style = "Dark" | |
self.theme_cls.primary_palette = "Orange" | |
return ( | |
MDScreen( | |
MDFlatButton( | |
text="Cause a popup", | |
line_color=(0, 0, 0, 0), | |
pos_hint={"center_x": .5, "center_y": .3}, | |
on_release=self.cause_a_popup | |
), | |
MDFlatButton( | |
text="Exit by pressing this button", | |
line_color=(0, 0, 0, 0), | |
pos_hint={"center_x": .5, "center_y": .6}, | |
on_release=self.stop | |
) | |
) | |
) | |
def cause_a_popup(self, _): | |
Logger.info("Caused a Popup") | |
AskDialog.ask("Enter some text:", self.when_text_entered) | |
def when_text_entered(self, entered_text): | |
Logger.info(f"At the popup, you entered {entered_text!r}") | |
if __name__ == '__main__': | |
TestApp().run() |
FWIW, the answer was wrapping the on_release
values in a lambda. Weird weird weird.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pressing the buttons doesn't work.