dimanche 31 juillet 2022

Python Tkinter Checkboxes created in function after user action

I am working on a small Python program that connects to a SQLite Database and allows the user to CRUD the data from several tables. I'm having a problem with some checkboxes that are not created until the user has made several other selections and pushed a button. The number of checkboxes and the initial state of each checkbox is not known until the user has made their selections and the queries have returned. The SQL queries are working correctly and the list of checkboxes is also created correctly but none of the checkboxes are checked initially even though the variable is correctly set based on the return of the SQL query. Here is a simplified version of my code that removes the SQL stuff but still has the problem.

from tkinter import *
ws = Tk()

def ViewTopics():
    titles = ["check1", "check2"]
    temp = [1,0]
    onoff = []
    i = 0
    for title in titles:
        if temp[i] > 0:
            onoff.append(IntVar(value = 1))
        else:
            onoff.append(IntVar(value = 0))
        i = i + 1
    i = 0
    for title in titles:
        l = Checkbutton(topicframe, text=titles[0], variable = onoff[i])
        l.grid(row=i+1, column=0, sticky=W)
        i = i + 1
        
topicframe = Frame(ws, padx=10, pady=10, relief='sunken', borderwidth = 1)
topicframe.grid(row=1, column=0, sticky=NSEW, padx=3, pady=3)

topicbutton = Button(ws, text = "Get Checkboxes", command=ViewTopics)
topicbutton.grid(row=0, column=0, sticky=EW)
    
ws.mainloop()

I have simplified this by hardwiring the titles array and the temp array. In the full code, these are filled in with information from the SQL queries. I know that my queries are working and that the arrays are correctly set up in my full code.

Note that the creation of the checkboxes must be in a loop because I don't know how many checkboxes there will be in advance. Also, I need to create the checkboxes in the function because I won't know what queries need to be run until the user makes some other selections (not included in this simplified code version) and then clicks the button.

If I print the onoff array in the second for-loop, the values are correct, but the first checkbox is not selected as intended. I have tried using l.select() in the second for-loop when onoff[i] is 1, but besides the fact that I shouldn't have to do that, it doesn't make a difference anyway.

I believe the problem is either with the use of a function or with the fact that the checkboxes are not created at the beginning like the other widgets. If I hardwire the arrays as I've done here and create the checkboxes without a function, they work correctly. But that doesn't meet the needs of my program.

Does anybody have any ideas on how to set this up correctly?




Aucun commentaire:

Enregistrer un commentaire