PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 8, 2022

[FIXED] How to make methods of Tkinter's class private?

 July 08, 2022     class, oop, python, python-3.x, tkinter     No comments   

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
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing