I have a GUI with an Option Menu that has a list of numbers (1:8). When a number is selected, an equal amount of buttons will be populated below. When those buttons are selected, a label next to it will be generated with the choice of folder locations. All that works great.
However, I want to be able to alter the number of buttons dynamically. When I increase the number of buttons, buttons are added, which is what I expect. However, I can't figure out how to remove buttons if say, I originally select 8, but reduce it to 4.
I'd also like to be able to increase/decrease the number dynamically.
I've already tried using grid_forget(), grid_remove() and destroy to try to remove that line/button/grid location off the grid, but nothing works.
Here's my original code:
import tkinter as tk
from tkinter import ttk, StringVar, filedialog, OptionMenu
from functools import partial
def main():
# Create a GUI to select the number of video folders
# root window
root = tk.Tk()
root.geometry("1200x500")
root.resizable(True, True)
root.title("Assign Videos")
class AssignVideos:
def __init__(self, master):
"""initializes the GUI with a dropdown to select the number of video cameras.
The selection will then create an equal number of prompts to select where the data
for each camera is stored"""
# Header to select the number of reference video cameras
self.number_of_cams_selection_header = ttk.Label(
text="Number of Videos:"
)
self.number_of_cams_selection_header.grid(column=0, row=0)
# Create an option menu with which to select the number of reference video cameras
self.select_number_of_cams = OptionMenu(
root,
StringVar(root, value=" "),
*[str(num) for num in range(1, 9)],
command=self.create_inputs,
)
self.select_number_of_cams.grid(column=1, row=0)
# Define variables that are going to be used later
self.number_of_cams = int
self.folder_path_label = {}
self.folder_path_button = {}
self.folder_path = {}
self.folder_path_selection = {}
def create_inputs(self, _):
"""Generates the equal number of folder selection inputs for the user to select the location of the VVIDs"""
self.number_of_cams = int(self.select_number_of_cams["text"])
for num in range(self.number_of_cams):
# Creates the label to select the folder path
self.folder_path_button[num] = ttk.Button(
root,
text=f"Select the Folder for Camera # " f"{num + 1}: ",
command=partial(self.select_folder, num)
)
self.folder_path_button[num].grid(column=1, row=num + 1)
def select_folder(self, num):
"""Places Buttons on the screen to select the folder"""
self.folder_path_selection[num] = filedialog.askdirectory()
self.folder_path[num] = ttk.Label(root, text=self.folder_path_selection[num])
self.folder_path[num].grid(column=2, row=num+1)
_ = AssignVideos(root)
root.mainloop()
if __name__ == "__main__":
main()