python - Kivy Python 中的按钮绑定(bind)

标签 python kivy

我想知道如何让我的代码工作。我有一个类创建一个带有按钮的弹出窗口。每个按钮都应该绑定(bind)到子类。但这不起作用。我的代码有什么问题吗?

class chooser:
def __init__(self):
    None
def show(self,title,options=["NOTHING"],size=(.5,.5)):
    self.bts = {}
    self.response = False
    self.content = FloatLayout()
    self.content.pos_hint = {"y":0,"x":0}
    # create buttons
    pos_cntr = 0
    for opt in options:
        self.bts[pos_cntr] = Button(text=opt)
        self.bts[pos_cntr].size_hint = 1,float(1)/float(len(options))
        self.bts[pos_cntr].pos_hint = {"x":0,"y":pos_cntr}
        self.bts[pos_cntr].bind(on_press=self.canceldia)
        self.content.add_widget(self.bts[pos_cntr])
        print "bound"
        pos_cntr += float(1)/float(len(options))
    self.pop = Popup(title=title,content=self.content,auto_dismiss=False)
    self.pop.size_hint = size
    self.pop.open()
def canceldia(self,instance):
    print "closing"
    self.response = instance.text
    self.pop.dismiss()
def getresponse(self):
    return self.response

我已经导入了所有需要的模块。

我是这样执行的:

c = chooser()
c.show("hello","world",["welcome","close","nothing","example"])

我已经创建了一个根小部件。弹出窗口工作正常,一切都创建得很好,但按钮没有绑定(bind)。请帮助我!

最佳答案

在循环中,您始终引用 self.bts[pos_cntr] ,因此您可以在每次迭代中覆盖它。这个怎么样?

for idx, opt in enumerate(options):
    self.bts[idx] = Button(text=opt)
    self.bts[idx].size_hint = 1,float(1)/float(len(options))
    self.bts[idx].pos_hint = {"x":0,"y":pos_cntr}
    self.bts[idx].bind(on_press=self.canceldia)
    self.content.add_widget(self.bts[idx])

关于python - Kivy Python 中的按钮绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29050670/

相关文章:

Python Flask,使用重新加载器重新启动 : What does that mean

python - pyarrow.ParquetDataset > 分区列的架构

python - django.db.utils.DatabaseError

android - Kivy:AsyncImage 和 Urllib 不会在 Android 上打开任何 url

python - 如何根据焦点设置Kivy TextInput背景颜色

android - Python - Kivy 是否在 Android 应用程序中实现 Activity ?

python - 如何从qt模型中获取所有数据

python - 根据重复条目条件过滤数据帧

python - kivy python 闪烁文本

python - 如何在python的kivy应用程序模块中更改屏幕背景的颜色?