Home > OS >  i dont undertand the loop, someone can explain my whats going on here? im beginner btw
i dont undertand the loop, someone can explain my whats going on here? im beginner btw

Time:09-18

basically i need help to understand the loop section, cause i dont get the steps. its an exercise from a course

from time import *

class MyFrame(Frame):
    def __init__(self):
        Frame.__init__(self)

        self.myCanvas = Canvas(width=300, height=200, bg='white')
        self.myCanvas.grid()

        self.myCanvas.create_rectangle(10, 10, 50, 50)
        self.myCanvas.update()

        sleep(1)

        self.myCanvas.create_rectangle(20, 20, 60, 60)

frame02 = MyFrame()
frame02.mainloop()```

CodePudding user response:

The mainloop is simply what is run once you are satisfied with the current state of all of your widgets and environment and are prepared to hand control of the app to the user.

Without the mainloop your program would build the widget, display it on the screen, then there would be no further instructions so the application would end and your window would be destroyed.

You should think of the mainloop as an idle process that listens for the user of the application to interact with it in some way.

Also see inline notes below.

from time import *

class MyFrame(Frame):   # This is the root widget class which subclasses the tkinter.Frame
    def __init__(self):   # This is the constructor method that is executed upon creation of the class instance.
        Frame.__init__(self)   # This calls the parent constructor for the tkinter.Frame

        self.myCanvas = Canvas(width=300, height=200, bg='white')  # This creates a canvas with a specific height width and background color
        self.myCanvas.grid()   # This places the canvas on the inside of the root widget class

        self.myCanvas.create_rectangle(10, 10, 50, 50)  # This creates a rectangle shape on the canvas 
        self.myCanvas.update()  # This updates the gui so you can see the rectangle

        sleep(1)    # this freezes the gui and all code execution for 1 second 

        self.myCanvas.create_rectangle(20, 20, 60, 60)  # this draws another rectangle on the canvas

frame02 = MyFrame()  # this creates the root frame widget instance and calls the constructor
frame02.mainloop()  # this starts the gui mainloop.
  • Related