个性化阅读
专注于IT技术分析

Python使用.kv文件在kivy中更改按钮颜色

Kivy是Python中与平台无关的GUI工具。由于它可以在Android, IOS, Linux和Windows等操作系统上运行。它基本上用于开发Android应用程序, 但这并不意味着它不能在桌面应用程序上使用。

在本文中, 我们将学习如何在kivy中更改按钮的背景颜色.kv文件.

background_color:有一个属性名称背景颜色, 用于更改kivy python中按钮的颜色。背景色kivy属性设置元素的背景色。将background-color属性指定为单一颜色值。语法:background_color:1、0、0、1

注意:默认情况下, 按钮的颜色为黑色, 并且只接受0到1之间的值

Basic Approach:

1) import kivy
2) import kivyApp
3) import Widget
4) import Button
5) Set minimum version(optional)
6) Create widget class
7) create App class
8) create .kv file (name same as the app class):
        1) Create Widget
        2) Create Button
        3) set the background color of the button as you want   
        4) Specify requirements
9) return Layout/widget/Class(according to requirement)
10) Run an instance of the class

Kivy教程–通过示例学习Kivy。

用于实现上述方法的代码, 以使用kv文件为按钮着色。

.py文件

## Sample Python application demonstrating the 
## How to change button color in Kivy using .kv file 
  
###################################################
# import modules 
import kivy 
  
# base Class of your App inherits from the App class. 
# app:always refers to the instance of your application 
from kivy.app import App 
  
# This layout allows you to set relative coordinates for children. 
from kivy.uix.relativelayout import RelativeLayout 
  
# To change the kivy default settings 
# we use this module config 
from kivy.config import Config 
  
# creating the root widget used in .kv file 
class RelativeLayout(RelativeLayout): 
     pass
  
# creating the App class in which name 
#.kv file is to be named Btn.kv 
class BtnApp(App): 
     # defining build() 
     def build( self ): 
         # returning the instance of root class 
         return RelativeLayout() 
  
# run the app 
if __name__ = = "__main__" : 
     BtnApp().run()

main.py文件的btn.kv文件实现

#.kv file implementation of color btn 
  
<RelativeLayout>: 
  
     Button: 
          
         text: "Colorful"
         # Change the default color to your choice
         background_color: 0.1 , 0.5 , 0.6 , 1
         pos_hint: { "x" : 0.2 , "y" :. 4 }
         size_hint: 0.3 , 0.2
  
  
     Button: 
         text: "Default"
  
         # The default color of a button
         background_color: 1 , 1 , 1 , 1
         pos_hint: { "x" :. 6 , "y" :. 4 }
         size_hint: 0.3 , 0.2

输出如下:

Python –使用.kv文件在kivy中更改按钮颜色1

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


赞(0)
未经允许不得转载:srcmini » Python使用.kv文件在kivy中更改按钮颜色

评论 抢沙发

评论前必须登录!