Kivy组件opacity视觉不更新:点击按钮切换组件显隐异常
Kivy组件修改opacity后仍不可见的问题排查
我来帮你捋捋这个问题——这不是Kivy的bug,是代码里的两个小细节没处理好导致的:
问题核心原因
SettingsEntryWidget的KV代码存在无效引用
在loginWidgets.kv里,SettingsEntryWidget的按钮事件写了:on_press: root.checkPswd(adminPswdLine.text)但
adminPswdLine是PasswordEntryWidget里的TextInput的ID,SettingsEntryWidget自己的子控件里根本没有这个ID。Kivy解析KV时遇到这个无效引用,会直接导致SettingsEntryWidget无法正常初始化——哪怕你后面把它的opacity改成1,它也没法正常渲染显示。未恢复SettingsEntryWidget的可交互状态
你在主KV文件里给SettingsEntryWidget设置了disabled: True,虽然disabled状态不会让组件完全消失(默认只是样式变灰),但如果要让组件正常可用,需要在显示它的时候把disabled设回False。
修复步骤
1. 修正SettingsEntryWidget的KV代码
把loginWidgets.kv里的按钮事件改成引用自身的TextInput ID(也就是host):
#:kivy 1.11.1 <PasswordEntryWidget>: orientation: "vertical" spacing: 20 TextInput: id: adminPswdLine multiline: False password: True size_hint_y: None height: 30 font_size: self.height - 10 Button: id: "takeAdminPswd" size_hint_x: 0.5 pos_hint: {'center_x': 0.5} on_press: root.checkPswd(adminPswdLine.text) <SettingsEntryWidget>: orientation: "vertical" spacing: 20 TextInput: id: host padding: [5, 2, 0, 5] text: "" multiline: False password: False size_hint_y: None height: 30 font_size: self.height - 10 Button: id: "takeSettings" size_hint_x: 0.5 pos_hint: {'center_x': 0.5} # 修正为引用当前Widget内的TextInput ID on_press: root.checkPswd(host.text)
2. 在显示SettingsEntryWidget时恢复可交互状态
修改Python代码里PasswordEntryWidget的checkPswd方法,加上恢复disabled状态的逻辑:
from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.boxlayout import BoxLayout from kivy.uix.screenmanager import ScreenManager, Screen from kivy.properties import NumericProperty from kivy.config import Config Config.set('graphics', 'width', '1920') Config.set('graphics', 'height', '1080') Config.set('graphics', 'fullscreen', 1) class FirstScreen(Screen): pass class SecondScreen(Screen): pass class MyScreenManager(ScreenManager): pass class PasswordEntryWidget(BoxLayout): def checkPswd(instance, pswd): if (pswd == "123"): instance.parent.opacity = 0 instance.parent.disabled = True settings_wgt = instance.parent.parent.ids.settingsWgt settings_wgt.opacity = 1.0 # 恢复组件的可交互状态 settings_wgt.disabled = False class SettingsEntryWidget(BoxLayout): def checkPswd(instance, pswd): if (pswd == "123"): print ("It's OK!") class MyApp(App): def build(self): return MyScreenManager() if __name__ == '__main__': MyApp().run()
验证效果
这样修改之后,输入正确密码点击按钮,PasswordEntryWidget会正常隐藏,SettingsEntryWidget应该就能正常显示出来,并且可以正常交互了。
内容的提问来源于stack exchange,提问作者Tobbor
相关产品推荐
相关产品推荐

