Python loop dictionary items through a tkinter GUI using a button
In your callBack method, globalvar = number + 1
does not update the value of the global variable globalvar
, it creates a new local variable called globalvar
. If you want the globalvar variable to be altered, you have to add global globalvar
in your method to explicitly refer to your global variable.
def callBack(number): global globalvar globalvar = number + 1 item(globalvar)
Note that using such a global variable, you do not need to have the value passed as a parameter and could just use Button(...,command=callBack)
Other remarks:
- with the grid geometry manager, you do not have to create the 20x14 "empty label" table (removing this loop will not change anything)
- in
item
method, instead of creating a Label, you could update the text of the existing one (it implies (1) holding a reference to the label in a variable (2) callconfig(text="new text")
on this reference). Creating new labels will reveal hazardous when replacing a label by a shorter (you are now just stacking them on top of others) - when you initialize B, L, I, V, you do not store anything in the variable. You store the answer of the call to
grid
(which is always None). To keep a reference on items you have to split your code in two lines :
L = Label(root, text="What comes in the following", fg="blue")L.grid(row=6, column=0)
So, what exactly is the problem? The title mentions looping through a dictionary. Tkinter is no different than any other library - you can do looping like you do for anything else.
For example:
for thing in ("Lettuce", "Cabbage", "Cheese"): var[thing] = IntVar() cb[thing] = Checkbutton(root, text=thing, variable=var[thing], ...) cb[thing].grid(...)
Is there something more you were looking for?