python - Kivy:KV 语言中的代码弹出关闭按钮

标签 python ubuntu-12.04 kivy

我正在尝试在 kivy 中编写一个自定义弹出窗口,以便从 ColorPicker 小部件中选择颜色。现在我正试图连接一个“确定”按钮来关闭弹出窗口,但它不起作用。弹出窗口显示正确,但是当我单击“确定”时,没有任何反应。弹出窗口继续出现在屏幕上。

这是我的 python 代码。

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()

这是KV代码。

<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()

非常感谢任何帮助。对不起所有的代码! :)

最佳答案

弹出窗口未关闭的原因是您将其直接添加到 PaintWindow 中这里:

<PaintWindow>:
    orientation: 'vertical'
    CPopup:

而不是实际调用方法 open()的弹出窗口。所以,

1 - 删除 CPopup:来自 kv 文件

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

2 - 调用 open()其他地方的方法。作为 build(self) 中的一个很好的例子的 PixPaint

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

以防万一,一些额外的东西:

  1. 你也可以去掉 id: cpopup关于 <CPopup>: 的定义并使用 root相反( on_press: root.on_press_dismiss() )。
  2. 此外,您可以摆脱 on_press_dismiss()并做 on_press: root.dismiss()相反。

关于python - Kivy:KV 语言中的代码弹出关闭按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20820638/

相关文章:

python - 如何诊断 "ImportError: cannot import name"

c++ - 如何在 Linux (Ubuntu) 中调整 Qt Creator for VTune Amplifier

python - Kivy:使用 on_press 事件在屏幕管理器中更改屏幕

android - Python 2.7 urllib.urlretrieve 未知的 url 类型 https

python - 将函数返回的值分配给Python中的变量

python - 如何从 nltk.trees 中识别和删除跟踪树?

python - 梯度下降曲线拟合

用于 linux 终端 shell 的 Python 3.3

mysql - 文件./ib_logfile101 : 'aio write' returned OS error 122

python - 创建 Kivy 应用程序时我总是遇到此错误