Помогите обратиться к елементу списка Python
У меня есть код, в котором в окне Tkinter`а цикл выводит название всех файлов в папке в фрейм. Но я хотел также добавить кнопки удаления и открытия этих файлов. Но я не знаю как обратиться к конкретному елементу, ведь каждый созданый фрейм - это отдельная итерация цикла For. код цикла:
self.arrcount =0
self.blocksCounter = 0
self.Height = 0.05
for i in range(self.file_count):
self.videoBlock = tk.Frame(self.mainFrame1, bg=self.darkColour)
self.videoBlock.place(relx=0.01, rely=self.Height, relwidth=0.95, relheight=0.2)
self.vTitle = tk.Label(self.videoBlock, bg = self.darkColour, fg = self.whitecolour, text = self.count[2][self.arrcount], anchor = tk.W, font = ('Helvetica', 14) )
self.vTitle.place(relx = 0.3, rely = 0.1, relwidth = 0.7, relheight = 0.2)
self.openBtn = tk.Button(self.videoBlock, fg = self.darkColour, bg = self.cactive,bd = 0, text = "Open" ,command=self.openfile)
self.openBtn.place(relx = 0.3, rely = 0.4, relwidth = 0.1, relheight = 0.25)
self.deleteBtn = tk.Button(self.videoBlock, bg= 'red', fg = self.whitecolour, text = "X", command = self.removeFile)
self.deleteBtn.place(relx = 0.94, rely = 0.65, relwidth = 0.05, relheight = 0.3)
self.Height += 0.22
self.blocksCounter += 1
self.arrcount +=1
self.file_count - Переменная которая хранит в себе количество файлов в папке self.count[][] - это список с названием файлов. Сам список:
('C:/Users/HP/Desktop/Empty Folder', [], ['Duke Dumont - Ocean Drive (Official Music Video).mp4', 'Joji - SLOW DANCING IN THE DARK.mp4', 'Lana Del Rey - Summertime Sadness (Official Music Video).mp4', 'masquerade.mp4', 'The Weeknd - Call Out My Name (Official Video).mp4'])
Сами фреймы и названия он выводит хорошо, как и все кнопки, но как допустим привязять функционал? Если попробовать такую функцию:
def removeFile(self):
self.mes = tk.messagebox.askquestion(title="Warning",icon='warning',message='Do you want to delete this fie?')
if self.mes == 'yes':
os.remove(self.count[2][self.arrcount])
print('File deleted')
else:
print('Deleting Canceled')
То код выдает ошибку:
IndexError: list index out of range
Ответы (1 шт):
Не вижу проблемы передавать имя файла в качестве параметра для функций открытия и удаления.
def removeFile(self, filename):
self.mes = tk.messagebox.askquestion(title="Warning", icon='warning',
message=f'Do you want to delete file "{filename}" ?')
if self.mes == 'yes':
os.remove(filename)
print('File deleted')
else:
print('Deleting Canceled')
self.arrcount =0
self.blocksCounter = 0
self.Height = 0.05
for i in range(self.file_count):
self.videoBlock = tk.Frame(self.mainFrame1, bg=self.darkColour)
self.videoBlock.place(relx=0.01, rely=self.Height, relwidth=0.95, relheight=0.2)
self.vTitle = tk.Label(self.videoBlock, bg = self.darkColour, fg = self.whitecolour, text = self.count[2][self.arrcount], anchor = tk.W, font = ('Helvetica', 14) )
self.vTitle.place(relx = 0.3, rely = 0.1, relwidth = 0.7, relheight = 0.2)
self.openBtn = tk.Button(self.videoBlock, fg = self.darkColour,
bg = self.cactive,bd = 0, text = "Open",
command=lambda: self.openfile(self.count[2][self.arrcount]))
self.openBtn.place(relx = 0.3, rely = 0.4, relwidth = 0.1, relheight = 0.25)
self.deleteBtn = tk.Button(self.videoBlock, bg= 'red',
fg = self.whitecolour, text = "X",
command = lambda: self.removeFile(self.count[2][self.arrcount]))
self.deleteBtn.place(relx = 0.94, rely = 0.65, relwidth = 0.05, relheight = 0.3)
self.Height += 0.22
self.blocksCounter += 1
self.arrcount +=1
Или, если хотите, можете передавать только индекс в списке (self.arrcount), раз уж сам список всё равно хранится.
(Правда я не понимаю зачем делать атрибутами класса локальные счётчики self.blocksCounter и self.arrcount, и чем они отличаются от переменной i)