Использовать изображение как кнопку в kivy

Опубликовано: 8 Апреля, 2022

Kivy - это платформенно-независимый инструмент с графическим интерфейсом на Python. Поскольку его можно запускать на Android, IOS, Linux, Windows и т. Д., Он в основном используется для разработки приложений Android, но это не означает, что его нельзя использовать в приложениях для настольных компьютеров.

Как мы уже обсуждали ранее, как работать с изображениями, а теперь мы узнаем, как использовать изображения и создавать с ними кнопку. В этой статье мы узнаем, как использовать изображение в качестве кнопки и как добавить к этому изображению функциональность и стиль.

To learn about it you must be aware about some properties, that are –

background_down :
1) Background image of the button used for the default graphical representation when the button is pressed.
2) background_down is a StringProperty .

background_normal :
1) Background image of the button used for the default graphical representation when the button is not pressed.
2) background_normal is also a StringProperty .

background_disabled_normal :
1) Background image of the button used for the default graphical representation when the button is disabled and not pressed.
2) background_disabled_normal is also a StringProperty .

Notes :
1) Now its only sufficient to understand that string property means they only take values in string that means like background_down: “normal.png” like this.
2) On click on the image it looks same like a simple button (as we uses it in a button).

В этой статье используются изображения:

normal.png:

down.png:

Basic Approach  :

-> import kivy
-> import kivy App
-> import button
-> set minimum version(optional)
-> Extend the class :  
              -> create an image a  button
              -> Do styling
              -> Arrange call back if needed 
-> Add and return a button
-> Run an instance of the class

Kivy Tutorial – Learn Kivy with Examples.

Simple Implementation that how to create a button using image
## Sample Python application demonstrating that   
## how to create button using image in kivy
       
##################################################      
# import kivy module 
import kivy 
     
# this restrict the kivy version i.e 
# below this kivy version you cannot 
# use the app or software 
kivy.require("1.9.1"
     
# base Class of your App inherits from the App class. 
# app:always refers to the instance of your application 
from kivy.app import App 
     
# creates the button in kivy 
# if not imported shows the error 
from kivy.uix.button import Button
   
# this restrict the kivy version i.e   
# below this kivy version you cannot   
# use the app or software   
kivy.require("1.9.0")  
      
# to change the kivy default settings we use this module config 
from kivy.config import Config 
      
# 0 being off 1 being on as in true / false 
# you can use 0 or 1 && True or False 
Config.set("graphics", "resizable", True)
   
     
# class in which we are creating the image button 
class ButtonApp(App): 
         
    def build(self): 
   
        # create an image a button 
        # Adding images normal.png image as button
        # decided its position and size 
        btn = Button(text ="Push Me !",
                     color =(1, 0, .65, 1),
                     background_normal = "normal.png",
                     background_down ="down.png",
                     size_hint = (.3, .3),
                     pos_hint = {"x":0.35, "y":0.3}
                   
      
        return btn 
             
     
# creating the object root for ButtonApp() class  
root = ButtonApp() 
     
# run function runs the whole program 
# i.e run() method which calls the target 
# function passed to the constructor. 
root.run()

Output:

Code to implement the styling and arranging a callback to the button –

## Sample Python application demonstrating that   
## how to create button using image in kivy 
      
##################################################      
# import kivy module 
import kivy 
    
# this restrict the kivy version i.e 
# below this kivy version you cannot 
# use the app or software 
kivy.require("1.9.1"
    
# base Class of your App inherits from the App class. 
# app:always refers to the instance of your application 
from kivy.app import App 
    
# creates the button in kivy 
# if not imported shows the error 
from kivy.uix.button import Button
  
# this restrict the kivy version i.e   
# below this kivy version you cannot   
# use the app or software   
kivy.require("1.9.0")  
     
# to change the kivy default settings we use this module config 
from kivy.config import Config 
     
# 0 being off 1 being on as in true / false 
# you can use 0 or 1 && True or False 
Config.set("graphics", "resizable", True)
  
    
# class in which we are creating the imagebutton 
class ButtonApp(App): 
        
    def build(self): 
  
        # create a fully styled functional button
        # Adding images normal.png and down.png
        btn = Button(text ="Push Me !",
                     background_normal = "normal.png",
                     background_down = "down.png",
                     size_hint = (.3, .3),
                     pos_hint = {"x":0.35, "y":0.3}
                   
    
        # bind() use to bind the button to function callback 
        btn.bind(on_press = self.callback) 
        return btn 
    
    # callback function tells when button pressed 
    def callback(self, event): 
        print("button pressed"
        print("Yoooo !!!!!!!!!!!"
            
    
# creating the object root for ButtonApp() class  
root = ButtonApp() 
    
# run function runs the whole program 
# i.e run() method which calls the target 
# function passed to the constructor. 
root.run()

Output:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

Next
Add image button using .kv file in kivy
Recommended Articles
Page :
Article Contributed By :
YashKhandelwal8
@YashKhandelwal8
Vote for difficulty
Article Tags :
  • Python-gui
  • Python-kivy
  • Python
Report Issue
Python

РЕКОМЕНДУЕМЫЕ СТАТЬИ