Python Kivy: 2组按钮,相互连接



也许有人会给我一个提示,我该往哪个方向走,因为我被我的问题困住了。我将非常感激。事情是这样的,我正在做我的Kivy项目。任务是用2个按钮唤起一行,其中一个按钮必须重命名另一个按钮。实际上它是有效的,但只有一行。如果我们有一组行,例如5行,无论您选择哪一行,只有第一行中的第一个按钮将被重命名,而不是指定一个。我正在尝试探索按钮集和按钮列表的索引,但不成功

py代码在这里:

class Radiators(Screen):
btn_lst = []
btn_cn_lst = []
i = 0
cn = 0
def add_button_radiator_setting(self):
self.i += 1
self.btn_rad = Button(text="room")
self.btn_lst.append(self.btn_rad)
self.ids.button_grid_radiators.add_widget(self.btn_rad)
self.cn = self.cn + 1
self.btn_context = Button(text="...")
self.btn_cn_lst.append(self.btn_context)
self.btn_cn_lst[self.cn-1].bind(on_press = self.rename_btn)
self.ids.button_context_menu.add_widget(self.btn_context)
def reject_button_radiator_setting(self):
self.ids.button_grid_radiators.remove_widget(self.btn_lst[self.i-1])
self.i -= 1
self.btn_lst.pop(-1)
self.ids.button_context_menu.remove_widget(self.btn_cn_lst[self.cn-1])
self.cn -= 1
self.btn_cn_lst.pop(-1)
def rename_btn(self, ind):
self.ids.button_grid_radiators.children[self.cn-1].text = str(input("enter: "))
class radiatorsApp(App):
pass

radiatorsApp().run()

关键代码在这里:

Radiators:
<Radiators>:
name: "Radiators"
BoxLayout:
orientation: "horizontal"
size_hint: 1, 0.1
pos_hint: {"top": 1}
Label:
text: "Radiators"
font_size: 32
BoxLayout:
orientation: "horizontal"
size_hint: 1, 0.8
BoxLayout:
size_hint: 0.15, 0.8
BoxLayout:
size_hint: 0.6, 0.8
GridLayout:
orientation: "tb-lr"
id: button_grid_radiators
row_force_default: True
row_default_height: 40
cols: 1
BoxLayout:
size_hint: 0.05, 0.8
GridLayout:
orientation: "tb-lr"
id: button_context_menu
row_force_default: True
row_default_height: 40
cols: 1
BoxLayout:
size_hint: 0.15, 0.8
BoxLayout:
size_hint: 1, 0.1
Button:
text: "<-- back to previous Window"
on_press: root.manager.current = "Heat System"
Button:
text: "Reset"
Button:
text: "-"
on_press: root.reject_button_radiator_setting()
Button:
text: "+"
on_press: root.add_button_radiator_setting()

on_press方法获取按下作为参数的Button。你可以用它来找到另一个Button:

def rename_btn(self, pressed_button):
index = self.btn_cn_lst.index(pressed_button)  # get index in list of Buttons
butt = self.btn_lst[index]  # get the Button from the other list at the same index
butt.text = str(input("enter: "))  # change the text of the Button

最新更新