In the tkinter app I'm building (win10 python 3.8) each time I open a new file I get a new list that I distribute to textboxes (Ok), combobox(ok), etc. When I open the first list checkbox loop builds ok, next file called checkboxes don't change. I can't update checkboxes, I mean, remove the previous list and insert another one. In the example I used to buttons (in app askopenfilename), lists build one bellow other. I need one replacing the other. I believe I need to use grid.clear() or destroy, but how? Thanks in advance.
from tkinter import *
root = Tk()
root.geometry('400x400')
my_friends = ['Donald', 'Daisy', 'Uncle Scrooge', 'Ze Carioca']
my_heroes = ['Captain America', 'Hulk', 'Spider Man', 'Black Widow',
'Wanda Maximoff', 'Vision', 'Winter Soldier']
what_list = ' '
def list_my_friends():
global what_list
what_list = my_friends
create_cbox()
def list_my_heroes():
global what_list
what_list = my_heroes
create_cbox()
def create_cbox():
for index, friend in enumerate(what_list):
current_var = tk.StringVar()
current_box = tk.Checkbutton(root, text= friend,
variable = current_var,
onvalue = friend,
offvalue = '')
current_box.pack()
button1= tk.Button(root, text = "my_friends",command=lambda:list_my_friends()).pack()
button2= tk.Button(root, text = "my_heroes",command=lambda:list_my_heroes()).pack()
root.mainloop()
CodePudding user response:
You can put those checkbuttons in a frame, then it is more easier to remove old checkbuttons before populating new checkbuttons:
def create_cbox():
# remove existing checkbuttons
for w in container.winfo_children():
w.destroy()
# populate new checkbuttons
for friend in what_list:
current_var = tk.StringVar()
# use container as the parent
current_box = tk.Checkbutton(container, text=friend,
variable=current_var,
onvalue=friend,
offvalue='')
current_box.pack(anchor='w')
tk.Button(root, text="my_friends", command=list_my_friends).pack()
tk.Button(root, text="my_heroes", command=list_my_heroes).pack()
# frame to hold the checkbuttons
container = tk.Frame(root)
container.pack(padx=10, pady=10)
CodePudding user response:
worked with little adjustments as I'm working in class:
class PageEight(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent) # parent is Frame
self.controller = controller
# to adequate to widgets outside the self.container_pg8:
self.rowspan_list = len(what_list)
#container:
self.container_pg8 = tk.Frame(self)
self.container_pg8.grid(row=2,
rowspan = self.rowspan_list,
column=1,)