我是Python的新手(版本3.6.1),刚刚开始使用Kivy作为我的GUI。我想要做的是在Kivy中创建一个命令行,让用户键入命令,处理命令,然后在同一文本框中输出需要输出的内容。#34;框。它应该像Windows命令行一样工作,但它必须是Kivy接口的一部分。 我最接近的是使用 kivy.uixTextInput ,但是,我不知道如何获取用户输入,然后如何打印到该文本框的输出。请帮助,我正在努力。
答案 0 :(得分:1)
在py文件中:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
class MainWindow(BoxLayout):
# We create a dictionary of all our possible methods to call, along with keys
def command_dict(self):
return {
'one': self.command_one,
'two': self.command_two,
'three': self.command_three
}
def process_command(self):
# We grab the text from the user text input as a key
command_key = self.ids.fetch_key_and_process_command.text
# We then use that key in the command's built in 'get_method' because it is a dict
# then we store it into a variable for later use
called_command = self.command_dict().get(command_key, 'default')
try:
# The variable is a method, so by adding we can call it by simple adding your typical () to the end of it.
called_command()
except TypeError:
# However we use an exception clause to catch in case people enter a key that doesn't exist
self.ids.fetch_key_and_process_command.text = 'Sorry, there is no command key: ' + command_key
# These are the three commands we call from our command dict.
def command_one(self):
self.ids.fetch_key_and_process_command.text = 'Command One has Been Processed'
def command_two(self):
self.ids.fetch_key_and_process_command.text = 'Command Two has Been Processed'
def command_three(self):
self.ids.fetch_key_and_process_command.text = 'Command Three has been Processed'
class MainApp(App):
def build(self):
return MainWindow()
if __name__ == '__main__':
MainApp().run()
在你的kv文件中,(我叫做mainapp.kv)
<MainWindow>:
Label:
text: 'This is a label'
TextInput:
# We give TextInput an id to reference it in the actual code
id: fetch_key_and_process_command
# We set multiline to False, so we can use the next property (on_text_validate)
multiline: False
# on_text_validate will called MainWindow's process_command() when a user presses enter
on_text_validate: root.process_command()