Manh Nguyen Huu Manh Nguyen Huu - 1 month ago 11
Python Question

Why does accessing an instance attribute in tkinter require brackets, while accessing an instance attribute in pygame require dot?

In

pygame
, I use
games.screen.width
to access the
width
attribute.

won_message = games.Message(value = "You won!",
size = 100,
color = color.red,
x = games.screen.width/2,
y = games.screen.height/2,
lifetime = 250,
after_death = games.screen.quit)


In
tkinter
I use
self.result['text']
to access the
text
attribute

self.result = Label(self, text='Result:?')
self.result.grid(row=0, column=3, sticky=W)
self.result['text'] = 'Finish'


Can anyone explain to me why there are different ways to access attributes?

Answer

For tkinter, these attributes aren't attributes of the object, they are attributes of the underlying tk widget for which the Tkinter class is merely a wrapper.

The canonical way to access these attributes is with the configure or cget methods. Tkinter provides a dict-like interface simply as a syntactic shorthand.

For example, the following two statements are identical:

self.result.configure(text="Finish")
self.result["text"] = "Finish"

as are these:

print(self.result.cget("text"))
print(self.result["text"])