【发布时间】:2018-07-28 04:44:19
【问题描述】:
我一直在尝试模拟一个命令行设计,它可以让我:
- 输入命令
- 执行它
- 在我输入的命令文本下方输出它。
所以我需要的是这样的:
command_one
命令一已被处理,这是输出
我已经部分完成了这项工作,但结果是输出文本覆盖了输入,而不是“加起来”。我遇到的另一个问题是,每次需要输入内容时,我都必须单击 TextInput 窗口,而不是在不使用鼠标的情况下继续输入命令。 p>
是否有任何解决方法可以帮助我解决这个问题?
这是我的代码:(mainapp.py)(changed)
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 __init__(self, **kwargs):
super(MainWindow, self).__init__(**kwargs) #This makes sure the kivy super classes from which MainWindow descends get initialized correctly.
self.command_dict = {
'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
old_text = command_key.strip()
# 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[old_text, '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 = "{}\n{}\n".format(old_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()
(mainapp.kv)
<MainWindow>:
Label:
text: 'This is a label'
TextInput:
id: fetch_key_and_process_command
multiline: True
Button:
id: process_command_button
text: "Process Command"
on_release: root.process_command()
出现的错误说:
第 21 行,在 process_command 中 called_command = self.command_dict().get[command_key, 'default'] TypeError: 'dict' 对象不可调用
【问题讨论】:
标签: python command-line command kivy textinput