因此,我尝试使用kivy框架编写简单的代码,我的代码通过字典查找某个值,该值在以后的阶段告诉我的代码哪些字典值需要作为下拉菜单输出,哪些输出dict值仅需要作为常规标签和文本输入输出。现在的问题出在我正在浏览的字典中描述了多个需要下拉的值。我希望下拉菜单的工作方式是,在下拉菜单中选择一个值来触发下拉菜单时,必须将文本更改为单击的按钮的文本。这是代码,我决定编写一个更简单的版本以供阅读。我想在代码下键入此代码,但我真的很想在堆栈Over Flow上写问题。您要查看的代码将创建两个按钮(触发下拉菜单),一个名为组0,另一个名为组1,但是当我单击组0下的一个下拉按钮时,组1的文本属性会更改,但是我实际上想更改组0按钮的text属性。当我解释时,我的代表没有任何意义,因此请告诉我是否需要澄清,我们将不胜感激。
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
test_floatie = FloatLayout()
# We wanna create 2 button that trigger a drop down
i = 0
# The loop that creates the two buttons
while i < 2:
# Create a drop down
dropdown = DropDown()
for index in range(10):
# Creating our button
btn = Button(text="Button"+str(index), size_hint_y=None, height=44)
# Sending button info to dropdown select function
btn.bind(on_release=lambda btn: dropdown.select(btn.text))
# Closing drop down after selection
btn.bind(on_release=dropdown.dismiss)
# Adding buttons to the drop down
dropdown.add_widget(btn)
# Simple if statement for positioning
if i == 0:
position = "left"
else:
position = "right"
# The button that triggers the drop down
dropButton = Button(text="Group"+str(i), size_hint=(0.4, 0.3), pos_hint={"top":1, position:1})
print(dropButton)
# Binding the button to a function that triggers the drop down
dropButton.bind(on_release=dropdown.open)
# Using the drop down select function to change the text of the button that triggers the drop down
dropdown.bind(on_select=lambda instance, x: setattr(dropButton, "text", x))
test_floatie.add_widget(dropButton)
i = i +1
# Running la app
class MainApp(App):
def build(self):
return test_floatie
MainApp().run()
答案 0 :(得分:1)
稍微简化了代码:
from functools import partial
test_floatie = FloatLayout()
# We wanna create 2 button that trigger a drop down
def select(drop_button, text, btn):
drop_button.text = text
# The loop that creates the two buttons
for position in ["left", "right"]:
# The button that triggers the drop down
dropButton = Button(text="Group " + position, size_hint=(0.4, 0.3),
pos_hint={"top": 1, position: 1})
# Create a drop down
dropdown = DropDown()
for index in range(10):
# Creating our button
btn = Button(text=position + str(index), size_hint_y=None, height=44)
# Sending button info to dropdown select function
# btn.bind(on_release=lambda btn: setattr(dropButton, "text", btn.text))
# btn.bind(on_release=lambda btn: select(dropButton, btn.text, btn))
btn.bind(on_release=partial(select, dropButton, btn.text))
# Closing drop down after selection
btn.bind(on_release=dropdown.dismiss)
# Adding buttons to the drop down
dropdown.add_widget(btn)
# Binding the button to a function that triggers the drop down
dropButton.bind(on_release=dropdown.open)
test_floatie.add_widget(dropButton)
# Running la app
class MainApp(App):
def build(self):
return test_floatie
MainApp().run()
请注意使用partial
而不是已注释掉的lambda
。
看来他们是同谋,但事实并非如此。(请参阅here)
如果要在循环中创建回调,并使用循环变量作为回调的参数,则应使用
partial
。lambda
在运行时评估变量,而partial
在创建partial
函数时评估。