如何获取在kivy中定义在屏幕小部件内的滑块的值
Posted
技术标签:
【中文标题】如何获取在kivy中定义在屏幕小部件内的滑块的值【英文标题】:How to get the value of slider which defined inside screen widget in kivy 【发布时间】:2018-06-25 05:02:40 【问题描述】:我正在制作一个 kivy 文件并与 python 文件链接。我在 kivy 的屏幕内定义了滑块,并认为在 python 内访问。但是在运行下面的 main.py 文件后出现这样的错误AttributeError: 'super' object has no attribute '__getattr__'
这里是 main.py
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition
class Maintenance(Screen):
pass
class ScreenManagement(ScreenManager):
pass
presentation = Builder.load_file("ex4.kv")
class ex4(App):
def __init__(self, **kwargs):
super(ex4, self).__init__(**kwargs)
def build(self):
return presentation
def my_value(self):
print(self.root.ids.slider1.value)
if __name__ == '__main__':
ex4().run()
ex4.kv
#:import SlideTransition kivy.uix.screenmanager.SlideTransition
ScreenManagement:
transition:SlideTransition()
Maintenance:
<Maintenance>:
name: 'screen1'
BoxLayout:
orientation: 'vertical'
Slider:
id: slider1
on_value:app.my_value()
【问题讨论】:
【参考方案1】:id slider1
属于Maintenace
类的实例。 id 的范围仅限于声明它的规则,因此,ScreenManagement
实例没有名为 slider1
的 id。
有几种方法可以解决它,例如使用属性,但我认为最简单的方法是将滑块的值作为参数传递给回调:
ex4.kv
#:import SlideTransition kivy.uix.screenmanager.SlideTransition
ScreenManagement:
transition: SlideTransition()
Maintenance:
<Maintenance>:
name: 'screen1'
BoxLayout:
orientation: 'vertical'
Slider:
id: slider1
on_value: app.my_value(self.value) # <<<<<<<<<<<
main.py:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition
class Maintenance(Screen):
pass
class ScreenManagement(ScreenManager):
pass
presentation = Builder.load_file("ex4.kv")
class Ex4(App):
def build(self):
return presentation
def my_value(self, value): # <<<<<<<<<<<
print(value)
if __name__ == '__main__':
Ex4().run()
请记住,您不需要builder.load_file
。如果您的 ex4.kv
与您的 main.py
位于同一目录中,则只需:
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition
class Maintenance(Screen):
pass
class ScreenManagement(ScreenManager):
pass
class Ex4(App):
def my_value(self, value):
print(value)
if __name__ == '__main__':
Ex4().run()
【讨论】:
#FJSevilla ***.com/users/7131499/fjsevilla 谢谢这么多问题已经解决了!!!以上是关于如何获取在kivy中定义在屏幕小部件内的滑块的值的主要内容,如果未能解决你的问题,请参考以下文章