Kivy 如何访问子小部件中的小部件
Posted
技术标签:
【中文标题】Kivy 如何访问子小部件中的小部件【英文标题】:Kivy How to Access Widgets inside Child Widgets 【发布时间】:2021-10-30 07:47:30 【问题描述】:在这段代码中,有一个按钮,我在主按钮内制作了一个切换按钮。在按下主按钮时,我希望切换按钮的状态为“向下”。我该怎么做?
主代码:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.uix.screenmanager import Screen,ScreenManager
class Main(Screen):
def onbtn(self,widget):
for child in self.ids.Fl.children:
if isinstance(child, ToggleButton): # This part is wrong... How to access Widgets inside child Widgets?
child.state='down'
class Manager(ScreenManager):
pass
kv=Builder.load_file("test2.kv")
screen=Manager()
screen.add_widget(Main(name="main"))
class Test(App):
def build(self):
return screen
Test().run()
Kv 代码:
<Main>:
name: "main"
FloatLayout:
id: Fl
Button:
id: btn1
text: "BTN 1"
size_hint: (.5,.3)
pos_hint: "center_x":.5,"center_y":.6
on_press:
root.onbtn(self)
ToggleButton:
id: tglbtn1 # How to Access this button to change its state to down
size: 80,80
text: "TGL BTN 1"
pos: 500,400
【问题讨论】:
【参考方案1】:只是改变:
class Main(Screen):
def onbtn(self,widget):
for child in self.ids.Fl.children:
if isinstance(child, ToggleButton): # This part is wrong... How to access Widgets inside child Widgets?
child.state='down'
到:
class Main(Screen):
def onbtn(self,widget):
for child in widget.children:
if isinstance(child, ToggleButton):
child.state='down'
传递给onbtn()
方法的widget
是Button
。
【讨论】:
以上是关于Kivy 如何访问子小部件中的小部件的主要内容,如果未能解决你的问题,请参考以下文章