Python/Tkinter: root as a class / initializing instance variables in a tkinter class

Question:

I have created a custom tkinter root window with customized title bar and other modifications, as a class. The class is saved in a module named ModRoot. The relevent code is as follows:

import tkinter as tk

class Rt(tk.Tk):
  def __init__(self,winhght,winwdth,apptitle):
    super().__init__()

    # initialize instance variables
    self.winhght = winhght
    self.winwdth = winwdth
    self.apptitle = apptitle

In the main application, this root window is created with two lines of code, and the addition of the mainloop.

import ModRoot
RootWindow = ModRoot.Rt(400,800,"App Title")
RootWindow.mainloop()

I have two questions:

First, this root window works fine but, as I have learned in the past, there are sometimes problems with a particular approach that are not immediately evident. So the first question is simply whether or not the above approach to creating a root window is acceptable and correct.

The second question has to do with initializing the instance variables (self.winhght = winhght and so on). Strangely enough, I have found that if I comment these lines out, the class works just as it did before. Yet, every tutorial on classes indicates that these variables must be initialized. If that’s the case, why is this class working with those lines commented out? And are they actually necessary?

Asked By: fmex

||

Answers:

So the first question is simply whether or not the above approach to creating a root window is acceptable and correct.

Yes, it’s acceptable.

Yet, every tutorial on classes indicates that these variables must be initialized. If that’s the case, why is this class working with those lines commented out? And are they actually necessary?

It’s impossible for us to say. Do you use self.winwdth, self.winhght, and self.apptitle anywhere else in the code? You only need to initialize them if you need them later.

Answered By: Bryan Oakley
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.