Advertisement
Guest User

控件自由布局.py

a guest
Feb 20th, 2020
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.20 KB | None | 0 0
  1. #pylint:disable=W0613
  2. # -*-coding:utf-8-*-
  3. import kivy
  4. from kivy.app import App
  5. from kivy.uix.floatlayout import FloatLayout
  6. from kivy.uix.button import Button
  7. from kivy.uix.label import Label
  8. from kivy.uix.textinput import TextInput#引入输入框
  9.  
  10. kivy.resources.resource_add_path('font/')
  11. font = kivy.resources.resource_find('DroidSansFallback.ttf')
  12.  
  13. class RootWidget(FloatLayout):
  14.     def __init__(self, **kwargs):
  15.         super(RootWidget, self).__init__(**kwargs)
  16.    
  17.         self.button_init =Button(
  18.         text='计算',
  19.         font_name = font,
  20.         size_hint=(None, None),
  21.         size=(200, 144),
  22.         pos_hint={'center_x': .2, 'center_y': .9}
  23.         )   # 按钮控件
  24.        
  25.         self.label = Label(
  26.         text='',
  27.         font_name = font,
  28.         size_hint=(None, None),
  29.         size=(200, 144),
  30.         pos_hint={'center_x': .5, 'center_y': .9}
  31.         )  # 标签控件,用于显示按钮状态
  32.        
  33.         self.textinput = TextInput(
  34.         text='',
  35.         font_name = font,
  36.         size_hint=(None, None),
  37.         size=(200, 144),
  38.         pos_hint={'center_x': .3, 'center_y': .6}
  39.         )  # 文本框控件,用于输入字符状态
  40.              
  41.         self.add_widget(self.button_init)  # 添加控件至布局
  42.         self.add_widget(self.label)
  43.         self.add_widget(self.textinput)
  44.  
  45.         self.button_init.bind(state=self.state_changed)  # 绑定按钮状态改变事件
  46.  
  47.     def state_changed(self, sender, state):
  48.         """处理按钮状态改变事件"""
  49.         c=self.textinput.text
  50.         str=c
  51.        
  52.         def is_number(s):
  53.             try:    
  54.                 float(s)
  55.                 return True
  56.             except ValueError:
  57.                 pass
  58.             try:
  59.                 import unicodedata
  60.                 unicodedata.numeric(s)
  61.                 return True
  62.             except (TypeError, ValueError):
  63.                 pass
  64.             return False
  65.            
  66.         if is_number(str):
  67.             a=float(str)
  68.             b="%.3f" % (a+2)
  69.             self.label.text=b
  70.         else:
  71.             self.textinput.text=''
  72.             self.label.text='输入数字错误'    
  73.                        
  74. class MainApp(App):
  75.     def build(self):
  76.         return RootWidget()
  77.  
  78. if __name__ == '__main__':
  79.     MainApp().run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement