How to make methods of Tkinter's class private?

Issue

Here’s the code of a window, using tkinter library and OOP. I want to make methods of class App private. But some of them, like method destroy in code below should be public

from tkinter import *
from tkinter import ttk

class App(Tk):
    def __init__(self):
        super().__init__()

        # window settings
        self.title("Private Attributes")
        self.resizable(width=False, height=False)


root = App()  # create window
root.title("Public Attributes") # this shouldn't work

ttk.Label(root, text="Close this window").pack()
ttk.Button(root, text="Close", command=root.destroy).pack() # this should work

root.mainloop()

Solution

If you want something that doesn’t expose one or more Tk methods, you should use composition rather than inheritance. For example,

 class App:
     def __init__(self):
         self._root = Tk()
         self._root.title("Private Attributes")
         self._root.resizable(width=False, height=True)

     def mainloop(self):
         return self._root.mainloop()


root = App()
root.title("Public Attributes")  # AttributeError
root.mainloop()  # OK

You’ll need to decide if the ability to limit access to various Tk methods (remember, you can still access self._root directly, but the name suggests that you are responsible for any errors stemming from doing so) outweighs the amount of boilerplate you’ll need to write to expose the methods you do want access to. (Reducing that boilerplate is beyond the scope of this answer.)

Answered By – chepner

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published