[英]Python, Kivy. Limit input values between two numbers with a TextInput filter
[英]Python, Kivy. Textinput thousands separator
我需要在kivy TextInput
中使用thousands separator
(例如:1 000 000 ),以便在键入时提高可读性。
编辑:这是一个简短的示例,其中label
显示空格分隔符,我在键入时需要在TextInput
中得到相同的结果。 我想我必须在MyTextInput class
中使用过滤,但我真的不知道从哪里开始。 你能帮我解决这个问题吗?
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.textinput import TextInput
from kivy.properties import ObjectProperty
from kivy.uix.floatlayout import FloatLayout
Builder.load_string("""
<Calc>:
first_num:first_num
second_num:second_num
result:result
MyTextInput:
id: first_num
size_hint: 0.3, 0.2
pos_hint: {"center_x": 0.2, "y": 0.7}
MyTextInput:
id: second_num
size_hint: 0.3, 0.2
pos_hint: {"center_x": 0.8, "y": 0.7}
Button:
text: "R E S U L T"
on_release:
root.multiplication()
size_hint: 0.3, 0.2
pos_hint: {"center_x": 0.5, "y": 0.4}
Label:
id: result
size_hint: 0.4, 0.2
pos_hint: {"center_x": 0.5, "y": 0.2}
"""
)
class MyTextInput(TextInput):
input_filter = ObjectProperty('int', allownone=True)
class Calc(FloatLayout):
first_num = ObjectProperty()
second_num = ObjectProperty()
result = ObjectProperty()
def multiplication(self):
x = int(self.first_num.text)
y = int(self.second_num.text)
self.result.text = '{:,}'.format(int(x*y)).replace(",", " ")
class myApp(App):
def build(self):
return Calc()
myApp().run()
您可以覆盖TextInput
object 的insert_text
方法以获得预期结果,
class MyTextInput(TextInput):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.input_filter = 'int' # Set value using the default property.
def insert_text(self, substring, from_undo = False):
# Override this super-class method.
if not substring.isdigit(): # Eliminates non digit character.
return
else:
cc, cr = self.cursor
text = self._lines[cr]
new_text = text[:cc] + substring + text[cc:]
int_str = new_text.replace(" ", "") # Removing any inbetween space.
new_text = '{:,d}'.format(int(int_str)).replace(",", " ") # Here insert seperator.
super().insert_text(substring, from_undo = from_undo)
self._set_line_text(cr, new_text) # Super-class method.
Clock.schedule_once(lambda dt : setattr(self, "cursor", (cc+2, cr))) # Advances the cursor.
您还需要对 method multiplication
进行一些修改。
def multiplication(self):
# First remove any inbetween space.
num_text_1 = self.first_num.text.replace(" ", "")
num_text_2 = self.second_num.text.replace(" ", "")
if num_text_1 and num_text_2: # Non empty values.
x = int(num_text_1)
y = int(num_text_2)
self.result.text = '{:,}'.format(int(x*y)).replace(",", " ")
else:
self.result.text = "" # Or, any other message.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.