我想创建某种列表或字符/单词序列,可以使用箭头键导航并使用enter进行选择,有没有办法在Python中简单地做这种事情?
答案 0 :(得分:0)
#!/usr/bin/python
import sys, tty, termios, os
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
current = 0
lst = []
for i in range(0,10):
lst.append(i)
while 1:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
os.system("clear")
for i in range(0,len(lst)):
if i == current:
print str(lst[i]) + "*"
else:
print str(lst[i])
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
if ord(ch) not in [27, 13]:
continue
elif ord(ch) == 27:
k = []
k.append(ord(sys.stdin.read(1)))
k.append(ord(sys.stdin.read(1)))
if k[0] == 91:
if k[1] == 65:
if current > 0:
current -= 1
elif k[1] == 66:
if current < len(lst)-1:
current += 1
elif ord(ch) == 13:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
break
print "you chose: " + str(current)
这是我编写的一些代码来演示它,我在十分钟内编写它因此它并不完美,但它在Linux上运行在python 2.7下。基本思路是将终端模式更改为原始输入输出,读取箭头键并输入,并更改指向当前所选菜单项的变量current
。正如我所提到的,我在10分钟内写完了这个,所以通过一些研究,你应该能够想出一个属于你自己的界面。如果您对此答案有任何疑问,请对其进行评论。
如果你想在windows上使用,试试msvcrt.getch(),你可以自己编写一个函数来清除屏幕或在windows等上使用os.system(“cls”)......
答案 1 :(得分:0)
这里是tkinter + python 3.4中的一些基本示例:
快速视频:video through a list using the keyboard
import tkinter
class aplicacion():
def __init__(self,principal):
self.counter = -1
self.list = ["a", "b", "c", "d", "e"] # here the list
self.right = principal
self.right.bind("<Right>", self.keyright)
self.left = principal
self.left.bind("<Left>", self.keyleft)
self.enter = principal
self.enter.bind("<Return>", self.keyenter)
self.label_texto = tkinter.Label(principal, text= "here the text appear in the list")
self.label_texto.grid(column=0, row=0)
def keyright(self, event):
if self.counter == len(self.list)-1:
print("ya recorrio toda la lista, se reiniciara")
self.label_texto.config(text = "ya recorrio toda la lista, se reiniciara")
self.counter = 0
self.show_list_element(self.counter)
else:
self.counter +=1
self.show_list_element(self.counter)
def keyleft(self, event):
if self.counter < -1:
self.counter = len(self.list) -1
self.show_list_element(self.counter)
else:
self.counter -=1
self.show_list_element(self.counter)
def keyenter(self, event):
self.choise = self.label_texto.cget("text")
self.label_texto.config(text = ("you select: " + self.choise))
def show_list_element(self, account):
self.account = account
print(self.list[self.counter])
self.label_texto.config(text = self.list[self.account])
#widgets
root = tkinter.Tk()
#resolucionX = root.winfo_screenwidth()
#resolucionY = root.winfo_screenheight()
#root.geometry(str(resolucionX)+"x"+str(resolucionY)+"+0+0")
root.title("List Exercise")
app = aplicacion(principal=root)
root.mainloop()