Why in tkinter you don't have to write init?

Question:

When I’m using Pygame, a python library, I have to write "pygame.init" to initiate all modules. However, when I’m using Tkinter, another library, I don’t have to use "tkinter.init". Why?
Thanks!

Asked By: Crackorium

||

Answers:

When I’m using Pygame, a python library, I have to write "pygame.init()" to initiate all modules. However, when I’m using Tkinter, another library, I don’t have to use "tkinter.init()". Why?

Each Python library comes with its own way of using it and own mechanisms implemented for event handling if the library provides methods for interacting with the user.

How to use the library is then explained in the documentation or can be inferred from the documentation coming along with each library method and printed on demand.

So the right answer to the question why you have to use the library this and not other way is as simple as maybe surprising:

Because the library requires to use it this and not other way.

By the way:

  • in Tkinter (newer versions of the module are named tkinter) the initialization is silently done within an initialization method __init__ of the class Tk when creating the root window with root = tkinter.Tk() and for the tkinter window coming up you need in addition to this initialization tkinter.mainloop().

Here a minimal tkinter code required to open a window (see comments for details/explanations):

import tkinter
root = tkinter.Tk()
tkinter.mainloop()
# ^-- requires root = tkinter.Tk() else:  
# ^-- RuntimeError: Too early to run the main loop: no default root window
  • in pygame it is not necessary to call pygame.init() to open a pygame window.

Here a minimal pygame code required to open a window, keep it opened and responding (see comments for details/explanations):

import pygame
# pygame.init()
# ^-- is NOT required
screen = pygame.display.set_mode((640,480)) 
# ^-- REQUIRED else: pygame.error: video system not initialized
# ^-- creates the pygame window which stays opened (but not responding)
# ^--    as long as the Python script runs

# v--REQUIRED to keep the pygame window opened and responding: 
running = True
while running:
    # Check for exit: 
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
Answered By: Claudio
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.