gpt4 book ai didi

Python kivy (kivyMD) 如何获取 MDDropdownMenu 的值

转载 作者:行者123 更新时间:2023-12-05 02:15:25 25 4
gpt4 key购买 nike

我试图在我的 kv 文件中获取 MDDropwdownMenu 的选择我正在通过以下代码使用 MDRaisedButton

 MDRaisedButton:
id: select_warning_image_Button
text: "Menu labels"
opposite_colors: True
elevation_normal: 0
on_release: MDDropdownMenu(items=app.menu_labels, width_mult=4).open(self)

在我的 main.py(见下文)中,我有一个名为 MainApp 的类,它继承自 App。在此类中,我创建了属性变量 menu_labels。我想使用函数 change_variable 将变量 VARIABLE 的值设置为菜单的值。但我似乎无法使用 self.change_variable(…)。当下拉列表中的特定值被选中时,是否有一个值可以触发一个函数?

# main.py
import …


class MainApp(App):
VARIABLE = ""

menu_labels = [
{"viewclass": "MDMenuItem",
"text": "Label1",
"on_release": self.change_variable("Label1")},
{"viewclass": "MDMenuItem",
"text": "Label2",
"on_release": self.change_variable("Label2")},
]

def change_variable(self, label):
self.VARIABLE = label

最佳答案

解决方案

在输出中,Label2被选中。有关详细信息,请参阅代码段、示例和输出。

kv文件

  1. <MDMenuItem>: 添加类规则
  2. 添加on_release要调用的事件 change_variable() App类中的方法并传递self.text

片段-kv文件

<MDMenuItem>:
on_release: app.change_variable(self.text)

例子

主.py
from kivy.app import App
from kivymd.theming import ThemeManager


class MainApp(App):
title = "KivyMD MDDropdownMenu Demo"
theme_cls = ThemeManager()

VARIABLE = ""

menu_labels = [
{"viewclass": "MDMenuItem",
"text": "Label1"},
{"viewclass": "MDMenuItem",
"text": "Label2"},
]

def change_variable(self, value):
print("\nvalue=", value)
self.VARIABLE = value
print("\tself.VARIABLE=", self.VARIABLE)


if __name__ == "__main__":
MainApp().run()

主.kv

#:kivy 1.11.0
#:import MDDropdownMenu kivymd.menu.MDDropdownMenu
#:import MDRaisedButton kivymd.button.MDRaisedButton

<MDMenuItem>:
on_release: app.change_variable(self.text)

Screen:
name: 'menu'
MDRaisedButton:
id: select_warning_image_Button
size_hint: None, None
size: 3 * dp(48), dp(48)
text: 'Menu labels'
opposite_colors: True
elevation_normal: 0
pos_hint: {'center_x': 0.1, 'center_y': 0.9}
on_release: MDDropdownMenu(items=app.menu_labels, width_mult=4).open(self)

输出

Img01 - MDDropdownMenu opened Img02 - Selected Label2

关于Python kivy (kivyMD) 如何获取 MDDropdownMenu 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51861245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com