如何在Kivy按钮on_press事件中隐藏Canvas与Rectangle
Hey there! I see you're trying to hide the background Rectangle in your login screen when the "Login" button is pressed. The tricky part here is that Canvas instructions (like Color and Rectangle) aren't widgets, so you can't just set their opacity property like you did with the labels and text inputs. Let's fix this with a simple boolean flag approach.
Step 1: Add a Boolean Property to Your Root Widget
First, in your Python code, define a BooleanProperty to control whether the background should be visible. This will let us toggle Canvas rendering directly from the button press.
from kivy.app import App from kivy.uix.widget import Widget from kivy.properties import BooleanProperty from kivy.lang import Builder Builder.load_file('your_login_ui.kv') # Replace with your actual kv file name class LoginScreen(Widget): show_background = BooleanProperty(True) # Flag to control background visibility def validate(self, username, password): # Your existing login validation logic goes here pass class MyLoginApp(App): def build(self): return LoginScreen() if __name__ == '__main__': MyLoginApp().run()
Step 2: Update Your KV Code to Use the Flag
Modify your kv code to only render the canvas.before instructions when show_background is True. We'll use Kivy's conditional syntax in the kv language for clean control:
<LoginScreen>: name: "cany" canvas.before: if root.show_background: Color: rgba: 1,1,1,1 Rectangle: size: self.size pos: self.pos source: 'rect4190.png' Label: id:user_lbl text:"User Name: " color: .9,.1,.1,1 pos: 40,400 TextInput: id:username_txt size: cm(4),cm(0.66) pos: 125,437 write_tab: False multiline: False Label: id:pass_lbl text: 'Password:' color: .9, 0.12, .1, 1 pos: 40,350 TextInput: id:password_txt size: cm(4),cm(0.66) pos: 125,387 write_tab: False multiline: False Button: id:btn_login size: cm(2.33),cm(0.66) text: 'Login' pos: 160,200 focus: True on_press: root.validate(username_txt.text,password_txt.text) user_lbl.opacity = 0 pass_lbl.opacity = 0 username_txt.opacity = 0 password_txt.opacity = 0 btn_login.opacity = 0 root.show_background = False # Toggle background off here
How This Works
- The
show_backgroundboolean acts as a switch: whenTrue, the Canvas draws your background; whenFalse, those instructions are skipped entirely. - Adding
root.show_background = Falseto the button'son_pressevent ensures the background disappears right when the user clicks "Login", matching the behavior of your other UI elements.
If you ever wanted to bring the background back later (like after a failed login), you just need to set root.show_background = True somewhere in your code.
内容的提问来源于stack exchange,提问作者mohamadreza

