Where in this code does the window build? tkinter python

Question:

I'm looking at the book "Programming python" by Mark Lutz in which there is an example on 9.27 that shows how to do tasks in a time method (after). which works great, but I wanted to ask in the community regarding the GUI of that example, I don't know when it creates the main window (root/raiz/=tk.Tk()) to be able to change title geometry even add an image with a additional label here I leave the code to see who can answer me.

from tkinter import *
class Alarm(Frame):
    def __init__(self, msecs=1000): # default = 1 second
        Frame.__init__(self)
        self.msecs = msecs
        self.pack()
        stopper = Button(self, text='Stop the beeps!', command=self.quit)
        stopper.pack()
        stopper.config(bg='navy', fg='white', bd=8)
        self.stopper = stopper
        self.repeater()
    def repeater(self): # on every N millisecs
        self.bell() # beep now
        self.stopper.flash() # flash button now
        self.after(self.msecs, self.repeater) # reschedule handler
if __name__ == '__main__': Alarm(msecs=1000).mainloop()

Answer:

When in your __init__() method of your Alarm class you invoke the constructor of the Frame , with Frame.__init__(self) you are not passing it as a parameter which is the "parent" of this Frame, so that at that moment its constructor creates the root window for that Frame to have a parent.

Since it's the Frame 's constructor that does it, you don't have a chance to change its title or geometry. To avoid it you have to:

  • Create the root window yourself with root = Tk()
  • Configure it to your liking
  • Pass it as a parameter to the Alarm constructor, so that Alarm can in turn pass it as a parameter to the Frame constructor. That is to say:
from tkinter import *
class Alarm(Frame):
    def __init__(self, parent=None, msecs=1000): # default = 1 second
        Frame.__init__(self, parent)  # Aqui se la pasamos a Frame
        self.msecs = msecs
        self.pack()
        stopper = Button(self, text='Stop the beeps!', command=self.quit)
        stopper.pack()
        stopper.config(bg='navy', fg='white', bd=8)
        self.stopper = stopper
        self.repeater()

    def repeater(self): # on every N millisecs
        self.bell() # beep now
        self.stopper.flash() # flash button now
        self.after(self.msecs, self.repeater) # reschedule handler

if __name__ == '__main__':
    # Aqui la creamos y configuramos
    root = Tk()
    root.title("Mi titulo")
    root.geometry("300x200")
    # Y se la pasamos al constructor de Alarm
    Alarm(parent=root, msecs=1000)
    root.mainloop()
Scroll to Top