从MDDropdownMenu单击MDMenuItem后,我在2个不同的按钮上更改按钮文本时遇到问题-只有一个按钮可以更改自己的文本。 每个按钮必须分别更改文本。
在这种情况下-两个按钮,两个下拉菜单,不同菜单中的不同标签以及每个按钮都有从下拉列表中选择的自己的文本。
有main.py:
from kivy.app import App
from kivymd.theming import ThemeManager
from kivy.uix.screenmanager import Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.anchorlayout import AnchorLayout
def toast(text):
from kivymd.toast.kivytoast import toast
toast(text)
class MyScreen(Screen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.menu_items = [
{
"viewclass": "MDMenuItem",
"text": "text%d" % i,
"callback": self.callback,
}
for i in range(1, 3)
]
def change_variable(self, value):
print("\nvalue=", value)
self.VARIABLE = value
print("\tself.VARIABLE=", self.VARIABLE)
def callback(self, *args):
toast(args[0])
class MainApp(App):
title = "KivyMD MDDropdownMenu Demo"
theme_cls = ThemeManager()
def build(self):
return MyScreen()
if __name__ == "__main__":
MainApp().run()
有main.kv:
#:import MDDropdownMenu kivymd.menus.MDDropdownMenu
#:import MDRaisedButton kivymd.button.MDRaisedButton
<MDMenuItem>:
on_release:
app.root.change_variable(self.text)
app.root.ids.mainbutton.text = self.text
<MyScreen>:
name: 'myscrn'
AnchorLayout:
anchor_y: 'center'
BoxLayout:
orientation: 'vertical'
size_hint: 0.1, 0.5
pos_hint: {'center_x': 0.5, 'center_y': 0.5}
spacing: dp(10)
MDRaisedButton:
id: mainbutton
size_hint: None, None
size: 3 * dp(48), dp(48)
text: 'MDButton1'
pos_hint: {'center_x': 0.5, 'center_y': 0.5}
opposite_colors: True
on_release: MDDropdownMenu(items=root.menu_items, width_mult=4).open(self)
MDRaisedButton:
id: secondbutton
size_hint: None, None
size: 3 * dp(48), dp(48)
text: 'MDButton2'
pos_hint: {'center_x': 0.5, 'center_y': 0.5}
opposite_colors: True
on_release: MDDropdownMenu(items=root.menu_items, width_mult=4).open(self)
感谢您的帮助,对于英语不好,我们深表歉意!
答案 0 :(得分:1)
该解决方案要求对Python代码和kv文件进行以下增强。
self.menu_button = None
class MyScreen(Screen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
...
self.menu_button = None
root.menu_button
的{{1}}事件中初始化on_release
MDRaisedButton:
替换为app.root.ids.mainbutton.text
app.root.menu_button.text