samedi 9 janvier 2021

tkinter: Why aren't my checkboxes checked by default?

I have function that enable user to edit object and part of it is creating new window in which there are entries in checkboxes for each variable, that should by default have values of variables already typed in earlier but I can't make my checkboxes to be checked be default.

For now I'm trying to check all checkboxes by default (I think if that will work few if statements won't change it and I will have appropriate solution to my problem).

This is piece of my code related to those checkboxes:

from tkinter import *


def editonclick():
    persons = ['User 1', 'User 2', 'User 3']
    person_labels = []
    person_checkboxes = []
    checkbox_var = []

    new_window = Toplevel()

    for person in persons:
        checkbox_var.append(IntVar(value=1))
        person_labels.append(Label(new_window, text=person))
        person_checkboxes.append(Checkbutton(new_window, variable=checkbox_var[-1]))

    for i in range(len(persons)):
        person_labels[i].grid(row=i, column=0)
        person_checkboxes[i].grid(row=i, column=1)


root = Tk()

editonclick()

mainloop()

I tried setting by default checkbox_var to IntVar(value=1) setting its value to 1 after appending it to list and selecting checkbox after creating it and none of it works, but when I also printed state of this checkbox_var like this:

Attempt:

from tkinter import *


def editonclick():
    persons = ['User 1', 'User 2', 'User 3']
    person_labels = []
    person_checkboxes = []
    checkbox_var = []

    new_window = Toplevel()

    for person in persons:
        checkbox_var.append(IntVar(value=1))
        person_labels.append(Label(new_window, text=person))
        print(checkbox_var[-1].get())
        person_checkboxes.append(Checkbutton(new_window, variable=checkbox_var[-1]))
        print(checkbox_var[-1].get())

    for i in range(len(persons)):
        person_labels[i].grid(row=i, column=0)
        person_checkboxes[i].grid(row=i, column=1)


root = Tk()

editonclick()

mainloop()

Even though output was:

1
1

None of checkboxes were checked.

So the question is what I can do to have these checkboxes checked by default?

Edit: I think that code above is MRE for my problem also when writting it I realized that when outside of function code works properly.

Tried also adding onvalue=1 and offvalue=0 and it also doesn't work.




Aucun commentaire:

Enregistrer un commentaire