我正在使用Python 3.x制作非商业的CLI程序,它具有一个主菜单和一个位于主菜单下方的子菜单。为了成为一个可用的程序,我想制作简单的键盘事件处理程序,我尝试了两个不同的程序包(pynput和键盘),但是我遇到了类似的问题。 假设程序具有如下主菜单:
main_menu = ['Show existing URLs',
'Add new URL',
'Update URL',
'Delete URL',
'Quit'
]
通常,程序有两个不同的文件,但是我在这里合并它们,我在上面显示菜单,如下所示:
import keyboard
def show_urls():
msg_show_urls = 'Pres any key to continue'
for index, link in enumerate(existing_urls()):
print(index+1, '\t', link)
print(msg_show_urls)
return any_key()
def add_new_url():
pass
def update_url():
pass
def del_url():
pass
def terminate():
pass
active_functions = [show_urls, add_new_url, update_url, del_url, terminate]
def program():
procedures = {key+1: value for key, value in enumerate(active_functions)}
i_message = "Please specify the action you would like to do with the number to the left of it: "
while True:
show_menu(main_menu)
procedures[make_selection(main_menu, len(main_menu),
input(i_message))]()
def show_menu(menu):
for index, item in enumerate(menu):
print(index+1, '\t', item)
def make_selection(active_menu, menu_length, selection=""):
wrong_choice = False
wc_str = 'Please specify the action you would like to do with the number to the left of it'
while True:
if not selection == "":
if selection.isnumeric():
try:
if not wrong_choice:
selection = int(selection)
if selection < 1 or selection > menu_length:
wrong_choice = True
selection = str(selection)
continue
else:
show_menu(active_menu)
print(wc_str)
selection = input('Action you would like to do: ')
wrong_choice = False
continue
except ValueError:
wrong_choice = True
continue
else:
return selection
else:
show_menu(active_menu)
print(wc_str)
selection = input('Action you would like to do: ')
continue
else:
show_menu(active_menu)
print('Entry can not be empty')
selection = input('Action you would like to do: ')
continue
def existing_urls():
return urls
# Keyboard handlers start
def any_key():
try:
keyboard.read_key()
print('\r\r')
except Exception as e:
print(e) # Give error code
def yes_no():
selections = ['y', 'Y', 'n', 'N']
with keyboard.Events() as events:
# print(events)
for event in events:
print(event)
# Keyboard handlers finish
# CONS AND VAR
# Program main menu
main_menu = ['Show existing URLs',
'Add new URL',
'Update URL',
'Delete URL',
'Quit'
]
# URLS
urls = [
'http://stackoverflow.com/',
'https://www.wikipedia.org/',
'https://www.google.com/'
]
if __name__ == '__main__':
program()
这是我目前的全部代码,如果对您来说它看起来很长或杂乱无章,请不要卡在上面。
当我运行此代码并选择1时,然后按Enter键,它会向我显示URL,但不等我按任何键,它会按两次Enter键,或者如果我按了另一个键,这次它将写我按下的键(我假设我可以抓住它)。因此,我尝试了一些我导入time
模块并在any_key()
函数中的行之间放置一个sleep命令的事情:
def any_key():
time.sleep(0.2)
try:
keyboard.read_key()
print('\r\r')
except Exception as e:
print(e) # Give error code
它开始等待我,但是如果我再次按下Enter键,它将按下两次Enter键,我也尝试使用keyboard.send()
方法发送不同的键,但是结果是相同的。并且使用sleep()
函数并非每次都有效。
我该怎么做才能使其正常工作?