我想从Kivy开始,因为我在Python中编码,但我发现它真的很难!你能否解释一下它的工作原理? 例如,即使这看起来很模糊(这是他们网站的第二个例子)。
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
class LoginScreen(GridLayout):
def __init__(self, **kwargs):
super(LoginScreen, self).__init__(**kwargs)
self.cols = 2
self.add_widget(Label(text='User Name'))
self.username = TextInput(multiline=False)
self.add_widget(self.username)
self.add_widget(Label(text='password'))
self.password = TextInput(password=True, multiline=False)
self.add_widget(self.password)
class MyApp(App):
def build(self):
return LoginScreen()
if __name__ == '__main__':
MyApp().run()
我想从一个基本应用程序开始,该应用程序要求用户输入并显示从中创建的内容。 例如,在没有任何GUI的基本Python中,它可能是:
def hex_enc(text_input):
return text_input.encode('hex')
def hex_dec(text_input):
return text_input.decode('hex')
while True:
text_input = raw_input('Input : ')
mode = raw_input('Mode : ').lower()
if ('encrypt' in mode):
print hex_enc(text_input)
else:
print hex_dec(text_input)
我想我需要一个textinput和一个标签,这将是textinput的结果。 但这非常混乱,我不知道并将所有这些都用于kivy课堂!
答案 0 :(得分:3)
好。这是一个仅在Python中实现的示例,没有.kv文件。我在那里有一些评论试图解释一步一步的情况。它会弹出一个文本框,用户可以在添加感叹号后输入内容并将其吐出标签。显然你可以做更多有趣的事情而不是添加标点符号,但我决定让这个例子保持简单。
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
class MyDumbScreen(BoxLayout): # Changed to a BoxLayout for simplicity
def __init__(self, **kwargs):
# Call the base class constructor :)
# Note that this is where it will pick up on any stuff you did in the
# .kv file (if you have one)
super(MyDumbScreen, self).__init__(**kwargs)
self.orientation = "vertical"
# Here we are just creating a text input
my_user_input = TextInput()
# Here we add it to MyDumbScreen's widget tree. If you skip this step,
# you'll never see your precious widget.
self.add_widget(my_user_input)
# This is the label that will hold a modified version of the user's
# input
my_output = Label(text="initial value")
self.add_widget(my_output)
# Here we create a callback function
# This callback will be called whenever the 'text' property of
# our TextInput is modified
def callback(instance, value):
my_output.text = value + "!"
# Here we "bind" the callback to the TextInput's 'text' property
# If you skip this step, you won't see the changes ever take place
my_user_input.bind(text=callback)
class MyApp(App):
def build(self):
return MyDumbScreen()
if __name__ == '__main__':
MyApp().run()
请注意,我通常认为这比使用.kv文件更复杂。
如果你走了那条路,你的班级定义将是这样的:
class MyDumbScreen(BoxLayout): # Changed to a BoxLayout for simplicity
pass
你的.kv文件看起来像这样:
<MyDumbScreen@BoxLayout>:
orientation: "vertical"
TextInput:
id: my_user_input
text: ""
Label:
id: my_output # This id isn't serving a purpose
text: my_user_input.text + "!"
使用.kv方法,您没有手动添加内容到窗口小部件树,或者自己编写/添加回调的所有噪音。
请记住,默认情况下,Kivy将根据App类的名称和.kv文件的名称加载kv文件,并且区分大小写会因操作系统而异。