在.kv文件中使用webbrowser报Invalid indentation缩进错误如何解决
你遇到的报错和webbrowser模块本身无关,是KV文件的缩进层级错误导致的。你目前把on_ref_press属性写在了text属性的内容缩进块中,KV解析器判定缩进层级超出了当前组件允许的范围,因此触发报错。
修复方案
方案1:直接调整KV代码缩进(快速修复)
把on_ref_press的缩进调整到和text属性同级,属于MDLabel的属性,而不是text的子级即可:
MDLabel: id: record_your_conversations_label6a size_hint_y: None height: self.texture_size[1] + 2*self.padding[1] padding: dp(15), dp(10) markup: True text: """ For many, this is the first introduction to master audio files making for a steep learning curve.\n I've searched for the tips [ref=Alitu][b][u]google[/u][/b][/ref], you are welcome! """ # 注意这里on_ref_press和text是同级,缩进和text对齐 on_ref_press: import webbrowser webbrowser.open('https://google.com')
方案2:逻辑迁移到py文件(更规范,推荐)
KV文件适合写布局视图,不建议写复杂业务逻辑,既容易出现缩进问题,也不利于后续维护,推荐把跳转逻辑放到App类中处理:
- 修改py文件,新增打开链接的方法:
from kivymd.app import MDApp from kivy.core.window import Window import webbrowser # 统一在py文件顶部导入模块 Window.size = (300, 530) class MainApp(MDApp): def build(self): self.theme_cls.primary_palette = 'Gray' self.theme_cls.primary_hue = '200' self.theme_cls.theme_style = 'Dark' # 新增打开链接的方法 def open_link(self, instance, ref): if ref == "Alitu": webbrowser.open('https://google.com') if __name__ == "__main__": app = MainApp() app.run()
- 修改KV文件,直接调用对应方法即可:
MDLabel: id: record_your_conversations_label6a size_hint_y: None height: self.texture_size[1] + 2*self.padding[1] padding: dp(15), dp(10) markup: True text: """ For many, this is the first introduction to master audio files making for a steep learning curve.\n I've searched for the tips [ref=Alitu][b][u]google[/u][/b][/ref], you are welcome! """ on_ref_press: app.open_link(*args)
注意事项
- KV文件对缩进要求非常严格,每个组件的属性必须和同组件的其他属性同级,不能嵌套到其他属性的内容块中
- 不建议在KV中写import语句,所有第三方模块的导入统一放到py文件顶部更稳妥
内容的提问来源于stack exchange,提问作者Edwin
相关产品推荐
相关产品推荐

