Kivy,Python3.5 - 将用户文本输入绑定到类中的方法
Posted
技术标签:
【中文标题】Kivy,Python3.5 - 将用户文本输入绑定到类中的方法【英文标题】:Kivy, Python3.5 - Bind user text input to method in class 【发布时间】:2016-07-10 11:39:53 【问题描述】:嘿,这可能是一个愚蠢的问题,而且很可能是,但这是一个愚蠢的问题,在过去的几天里让我非常沮丧,所以我只想问,你们中的任何人都可以帮忙吗我将单行文本输入绑定到类中的方法?这是我的代码,我是新手,因此欢迎对其提出任何其他批评,它将帮助我改进,并感谢您提前抽出时间。
#//Random number generator//
import kivy
kivy.require('1.7.0')
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.properties import ObjectProperty
from kivy.event import EventDispatcher
from kivy.properties import StringProperty
from kivy.uix.boxlayout import BoxLayout
import string
import random
from kivy.lang import Builder
Builder.load_string("""
<RootWidget>:
BoxLayout:
orientation: 'horizontal'
canvas.before:
Rectangle:
pos: self.pos
size: self.size
source: "code.jpg"
BoxLayout:
orientation: "vertical"
padding: 20
spacing: 10
AsyncImage:
source: "img.png"
size_hint: 1, 1
pos_hint: 'center_x':.5, 'center_y': .5
Label:
id: label_1
text: root.data_model.c
font_size: 17
text_size: self.width, None
color: [0,255,0]
size_hint_y: .3
pos_hint_y: 'center_x':.5, 'center_y': .5
#-----------> Here <-------------
TextInput:
id: txt_inpt1
text: "Lenght (optional)"
size_hint_y: .2
on_text: root.check_status(f_but)
# --------------> And Here <-----------------
TextInput:
id: txt_inpt2
text: "Specific characters (optional)"
size_hint_y: .2
on_text: root.check_status(f_but)
Button:
id: btn_1
text: "Generate"
pos_hint_y:
on_press: root.button_press()
size_hint_y: .3
""")
class DataModel(EventDispatcher):
b = StringProperty("")
c = StringProperty("")
def __init__(self, *args, **kwargs):
super(DataModel, self).__init__(*args, **kwargs)
self.bind(b=self.set_c)
def set_c(self, instance, value):
self.c = self.b
class RootWidget(BoxLayout):
data_model = ObjectProperty(DataModel())
def button_press(self, *args):
#---------> I want size to equal txt_inpt1 and chars txt_inpt2 <----------
def id_generator(size=12, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
text = id_generator()
self.data_model.b = text
print (self.data_model.c)
class TestApp(App):
def build(self):
return RootWidget()
app = TestApp()
app.run()
【问题讨论】:
【参考方案1】:您可以使用ids
属性(字典)访问这些小部件:
def id_generator():
try:
size = int(self.ids['txt_inpt1'].text)
except ValueError:
size = 12
chars = self.ids['txt_inpt2'].text or (string.ascii_uppercase + string.digits)
return ''.join(random.choice(chars) for _ in range(size))
【讨论】:
以上是关于Kivy,Python3.5 - 将用户文本输入绑定到类中的方法的主要内容,如果未能解决你的问题,请参考以下文章
(Kivy/Python)当用户点击输入时从 textinput 小部件存储文本