如何在Kivy的Python文件中为Button控件显示图片
Let's walk through the problems in your current code and get that image button working properly:
1. Invalid Image Source
Your source=('Image') is not a valid image reference. This should be the full filename or relative path of your actual image file (like 'button_icon.png'), not just the word "Image". The parentheses here are also unnecessary—you only need to pass a string directly.
2. Broken on_press Binding
on_press="Screen" won’t work because Kivy expects a callable function/method for this event, not a plain string. You need to define a method that handles the button press (like switching screens, which it looks like you’re aiming for) and bind that method to the button.
3. Missing Size Configuration (Critical for Visibility)
If you don’t set size_hint or size for the Button, it will default to a tiny size, and your image won’t be visible. Adding these properties ensures the button is large enough to display your image.
Corrected Working Example
Here’s a full, tested code snippet that fixes all these issues:
from kivy.app import App from kivy.uix.button import Button from kivy.uix.screenmanager import ScreenManager, Screen class MainScreen(Screen): def __init__(self, **kwargs): super().__init__(**kwargs) # Create the image button with proper configuration img_button = Button( source='my_button_image.png', # Replace with your image's actual path/name pos_hint={"x":0.3, "top":0.3}, size_hint=(0.2, 0.1), # Adjust relative size to your needs on_press=self.switch_to_target_screen # Bind to your press handler ) self.add_widget(img_button) def switch_to_target_screen(self, instance): # Logic to switch screens (adjust based on your ScreenManager setup) self.manager.current = 'target_screen' class TargetScreen(Screen): pass class MyApp(App): def build(self): sm = ScreenManager() sm.add_widget(MainScreen(name='main')) sm.add_widget(TargetScreen(name='target_screen')) return sm if __name__ == '__main__': MyApp().run()
Key Tips to Troubleshoot Further:
- Image Path Check: Ensure your image file is in the same folder as your Python script, or use a relative path like
'assets/button_icon.png'if it’s in a subfolder. Kivy supports PNG, JPG, and other common image formats. - Screen Setup: The
switch_to_target_screenmethod assumes you’re using aScreenManager(since you referenced "Screen" in your original code). If you’re not using screens, replace this method with whatever action you want the button to trigger. - Size Tweaks: Use
size=(200, 50)for fixed pixel dimensions if you don’t want relative sizing withsize_hint.
If the image still doesn’t show up, double-check that the filename is spelled correctly (case-sensitive on most systems) and that the image file isn’t corrupted.
内容的提问来源于stack exchange,提问作者Adam Kamil

