python 2.7 using tkinter -all checkbox are being checked when click on one only

前端 未结 1 1491
天涯浪人
天涯浪人 2021-01-28 22:14

I\'m using python 2.7 with Tkinter (new to Tkinter:)) I have UI with list of 20 checkboxes once I click on one checkbox, all checkboxes are being checked, instead of one. In cod

相关标签:
1条回答
  • 2021-01-28 22:39

    The reason this happens is because you've given all of your Checkbutton widgets the same variable for their variable attribute.

    Meaning that as soon as one of the Checkbutton widgets is ticked self.var is given a value of 1 which means that all of the Checkbutton widgets have a value of 1 which equates to them having been selected.

    In short, whenever one is ticked it updates the value of all the other's because they have the same variable used to store their value.

    See this in the example below:

    from tkinter import *
    
    root = Tk()
    var = IntVar()
    
    for i in range(10):
        Checkbutton(root, text="Option "+str(i), variable = var).pack()
    
    root.mainloop()
    

    To resolve this you need to use a different variable for each Checkbutton, like the below:

    from tkinter import *
    
    root = Tk()
    var = []
    
    for i in range(10):
        var.append(IntVar())
        Checkbutton(root, text="Option "+str(i), variable = var[i]).pack()
    
    root.mainloop()
    
    0 讨论(0)
提交回复
热议问题