I'm having a bit of trouble with something, and I don't know how I could do it.
Well, I'm creating a dynamic form with buttons that adapts to how many files (in this case, movies) there are in a directory.
I have got this so far:
path="C:\\Users\\User\\Desktop\\test\\" # insert the path to the directory of interest
movies = []
dirList=os.listdir(path)
for fname in dirList: # loops through directory specified
print fname # prints file name
movies.append(fname) # adds the file name to list
my_form = form.Form([form.Button("btn", id="btn" + movies[i], value = i, html=movies[i], class_="btn" +movies[i]) for i in range(len(movies))])
However, I want the list comprehension/generator to make my_form
look something like this:
my_form = form.Form(
form.Button("btn", id="btnA", value="A", html="Movie1", class_="btnA")
form.Button("btn", id="btnB", value="B", html="Movie2", class_="btnB")
)
As you can see instead of the movie name being the id, it is btnA
or btnB
.
So how could I generate that output?
I think you want to do something like:
from string import ascii_uppercase
buttons = [form.Button("btn", id="btn{0}".format(char), value=char,
html=movie, class_="btn{0}".format(char))
for char, movie in zip(ascii_uppercase, movies)]
my_form = form.Form(buttons)
This uses the letters in string.ascii_uppercase
to label each item in movies
.
If I understand correctly, you want the id to be btn + a letter according to the index of the movie?
you can use this code:
def letterForIndex(idx):
return chr(ord('A')+idx)
so you would do :
my_form = form.Form([form.Button("btn", id="btn" + letterForIndex(i),
value = letterForIndex(i), html=movies[i], class_="btn" +letterForIndex(i)) for i in range(len(movies))])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.