[Python] How can I make a checklist with checkboxes?

Discussão em 'Python' iniciado por Stack, Março 26, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to make a checklist with checkboxes that I can click by clicking the checkboxes.

    I tried some code from How to create Checkboxes from list, but it gives me an error. I know how to code some basic programs, but not more complex ones. This is my code:

    import tkinter as tk

    class CheckbuttonList(tk.LabelFrame):
    def __init__(self, master, text=None, list_of_cb=None):
    super().__init__(master)

    self['text'] = text
    self.list_of_cb = list_of_cb
    self.cb_values = dict()
    self.check_buttons = dict()

    if self.list_of_cb:
    for item in list_of_cb:
    self.cb_values[item] = tk.BooleanVar()
    self.check_buttons[item] = tk.Checkbutton(self, text=item)
    self.check_buttons[item].config(onvalue=True, offvalue=False,
    variable=self.cb_values[item])
    self.check_buttons[item].pack()



    if __name__ == '__main__':

    root = tk.Tk()

    my_list = ["item1", "item2", "item3"]

    my_cbs = CheckbuttonList(root, "My Checkbox List", my_list)
    my_cbs.pack()

    root.mainloop()


    This is the error I keep getting:


    Traceback (most recent call last): File "/home/main.py", line 24, in root = tk.Tk() File "/usr/lib/python3.10/tkinter/init.py", line 2299, in init self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) _tkinter.TclError: couldn't connect to display ":1"
    ​

    BTW I'm using an online compiler to test this, but I used the python program as well and got the same error.

    Continue reading...

Compartilhe esta Página