lundi 11 octobre 2021

tkinter Checkbox from list loop. How rebuild (update) checkboxes when new list arrives?

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() 



Aucun commentaire:

Enregistrer un commentaire