LittleWing
LittleWing

Reputation: 21

Can't figure out the nested for loop part and how does it work in this code

I'm Trying to figure out this code that I found online. I don't understand how the nested loop actually provides the results in this specific tkinter program (four cases). I used print statements in key parts in order to understand it, but the more I dive in the more confused I get.

Can someone please explain how the code works?

from tkinter import *

class App:
    def __init__(self, root, use_geometry, show_buttons):
        fm = Frame(root, width=300, height=200, bg="blue")
        fm.pack(side=TOP, expand=NO, fill=NONE)

        if use_geometry:
            root.geometry("600x400") ### (1) Note geometry Window Manager method


        if show_buttons:
            Button(fm, text="Button 1", width=10).pack(side=LEFT)
            Button(fm, text="Button 2", width=10).pack(side=LEFT)
            Button(fm, text="Button 3", width=10).pack(side=LEFT)

case = 0
for use_geometry in (0, 1):
    for show_buttons in (0,1):
        case = case + 1
        root = Tk()
        root.wm_title("Case " + str(case)) ### (2) Note wm_title Window Manager method
        display = App(root, use_geometry, show_buttons)
        root.mainloop()

Upvotes: 1

Views: 63

Answers (1)

Hultner
Hultner

Reputation: 3780

If I read your question correctly you're wondering how you can end up with our iterations with the following loop-statement.

for use_geometry in (0, 1):
    for show_buttons in (0,1):

Reason is that for both use_geometry = 0 and use_geometry = 1 we will run the inner loop resulting in the following four cases:

# First outer iteration, first inner
{ use_geometry = 0, show_buttons = 0 }

# First outer iteration, second inner
{ use_geometry = 0, show_buttons = 1 }

# Second outer iteration, first inner
{ use_geometry = 1, show_buttons = 0 }

# Second outer iteration, second inner
{ use_geometry = 1, show_buttons = 1 }

# Done

In total four combinations. For each of these four combinations you're creating a new Tk()and App()-instance, thus four instances in total.

Upvotes: 1

Related Questions