Search code examples
pythontkinterpycharmprotected

Python - what does "add property for the field" do?


I'm developing a python program in pycharm. Under this line of my code:

rut = Tk()
rut.tk.call('wm', 'iconphoto', rut._w, PhotoImage(file=icon_file))

And I get a warning on 'rut._w' saying:

access to a protected member _w of a class

And when I press ctrl + enter it gives me an option:

add property for the field

And when I click on it it changes the line to:

rut.tk.call('wm', 'iconphoto', rut.w, PhotoImage(file=icon_file))

But I know that is not all what it does because if I manually change the name I will get:

AttributeError: '_tkinter.tkapp' object has no attribute 'w'

So what is happening here? what what does _w mean and what about .w and what does it mean to add property for the field and how is it actually done?

Please note that Tk is imported from the tkinter package which is not in my project files so I suppose pycharm can't edit it.


Solution

  • The __str__ method defined for Tk returns self._w i.e. it is a getter for the private property.

    You can use:

    rut.tk.call('wm', 'iconphoto', str(rut), PhotoImage(file=icon_file))
    


    What Pycharm is doing is adding this to Tkinter class. This is bad because your application is guaranteed to work on your machine but not on other machines where the Tkinker class isn't so patched.

    Cmd + Click or Ctrl + Click (depending on your platform) on the Tk() in rut = Tk() to open the class definition. You'll see this added at the end.

    @property
    def w(self):
        return self._w