Home > Blockchain >  Python/tkinter - defining checkbox looping over a string of labels
Python/tkinter - defining checkbox looping over a string of labels

Time:10-04

I want to define a row of tk checkbox widget looping on a list of labels. Everything works fine except that I can't seem to be able to set the IntVar value on the if statement, although it works for the state. What am I doing wrong?

def CheckboxLine(self, frame, fformat=None):
    self.__set_col(0) # set widget column to zero
    var_c = [] 
    widget_c = []

    if fformat is None:
        fformat = ['text', 'excel', 'xml']

    # widget definition
    for item in fformat:
        var_c.append(tk.IntVar(master=frame))
        widget_c.append(tk.Checkbutton(master=frame, text=item, variable=var_c[-1]))
        if item == 'text':
            var_c[-1].set(1)
            widget_c[-1]['state']='disabled'
        else:
            var_c[-1].set(0)
            widget_c[-1]['state']='normal'
        widget_c[-1].grid(row=self.__row, column=self.__col, columnspan=1, padx=self.__padx, pady=self.__pady, sticky="nsew")
        self.__next_col()
    self.__next_row()

CodePudding user response:

Define var_c and widget_c outside of your function. The reason behind this is unclear to me, unfortunately.

import tkinter as tk

root = tk.Tk()
var_c = []
widget_c = []

def CheckboxLine(frame, fformat=None):

    if fformat is None:
        fformat = ['text', 'excel', 'xml']

    # widget definition
    for idx, item in enumerate(fformat):
        var_c.append(tk.IntVar(value=0))
        widget_c.append(tk.Checkbutton(master=frame, text=item, variable=var_c[-1]))
        if item == "text":
            var_c[-1].set(1)
            widget_c[-1]["state"] = "disabled"
        widget_c[-1].grid(row=idx, column=0)

CheckboxLine(root)
root.mainloop()
  • Related