我正在文件
info_options.kv
中的 StackLayout 中创建一个按钮。现在,每当按下此按钮时,我想调用 InfoOptionsPanel
类中的函数。当我用 return MainPanel()
替换 return InfoOptionsPanel()
时,即当我不使用 MainPanel
创建的布局时,我可以调用此函数,但是当我使用 gui 的 MainPanel
类时,按钮会给出下面,还要注意,即使在 GUI 中使用 MainPanel
,GUI 中也没有问题。
抛出错误
File "C:\Users\..\AppData\Local\Programs\Python\Python312\Lib\site-packages\kivy\lang\builder.py", line 60, in custom_callback
exec(__kvlang__.co_value, idmap)
File "K:\path\to\project\Info_options.kv", line 5, in <module>
on_press: self.parent.on_press()
^^^^^^^^^^^^^^^^
AttributeError: 'InfoOptionsPanel' object has no attribute 'on_press'
信息.kv
<InfoPanel@BoxLayout>
orientation: 'vertical'
size_hint_y: 0.8
pos_hint: {"top": 1}
Label:
id: info_label
text:"Click button"
font_size:50
info_options.kv
<InfoOptionsPanel@StackLayout>:
orientation: 'lr-tb'
Button:
text: 'Button'
on_press: self.parent.on_press()
size_hint :.7, 0.1
主屏幕.kv
<MainPanel@BoxLayout>:
orientation: 'vertical'
AnchorLayout:
anchor_x: 'left'
anchor_y: 'top'
InfoPanel:
size: 100, 100
AnchorLayout:
anchor_x: 'right'
anchor_y: 'bottom'
InfoOptionsPanel:
size: 100, 100
主.py
from kivy.app import App
from kivy.lang.builder import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.stacklayout import StackLayout
import os
kivy_design_files = ["Info_options", "Info", "main_screen",]
for kv_file in kivy_design_files:
Builder.load_file(os.path.join(os.path.abspath(os.getcwd()), kv_file + ".kv"))
class InfoPanel(BoxLayout):
pass
class InfoOptionsPanel(StackLayout):
def on_press(self):
print("Button pressed\n"*55)
class MainPanel(BoxLayout):
pass
class MyApp(App):
def build(self):
return MainPanel()
if __name__ == '__main__':
MyApp().run()
您不需要在
main.py
和 kivy 文件中继承 Kivy 的布局类。从 main.py
或您的 kivy 文件中删除继承。
对于
main.py
,
class InfoPanel(): # don't inherit from BoxLayout
pass
class InfoOptionsPanel(): # don't inherit from StackLayout
def on_press(self):
print("Button pressed\n"*55)
class MainPanel(): # don't inherit from BoxLayout
pass
或者对于 kivy 文件(在每个文件中执行相同的操作),
<InfoOptionsPanel>: # removed @StackLayout
orientation: 'lr-tb'
Button:
text: 'Button'
on_press: root.on_press()
size_hint :.7, 0.1
我建议你从 main.py 中删除继承并保持 python 代码的美观和干净。 Kivy 文件旨在处理 UI,因此请充分利用这一点。
此外,请使用
root.on_press()
代替 self.parent.on_press()
。无论如何,两者都可以工作,但是 root
澄清您指的是根小部件。如果您将来向 self.parent
添加多个父小部件或布局,Button
将引用其他一些小部件。