Are Widgets Classes or Methods in Tkinter?

Viewed 212

A text widget is created by using the Text() method.

import tkinter as tk 
root = tk.Tk()
T = tk.Text(root, height=2, width=30) 
T.pack() 
T.insert(tk.END, "Just a text Widget\nin two lines\n") 
w = tk.Label(root, text="Hello Tkinter!") 
w.pack() 
root.mainloop()

I am new to Python. My understanding is that Text and Label are classes and T and w are the objects created from Text and Label classes. But in the above text example, a website mentioned that

A text widget is created by using the Text() method.

I am totally confused now. pack() is a method and we can apply methods on the objects (T and w here) that we created from classes like Label and Text.

Please let me know if the widgets like Label, Text, Button, etc. are classes or methods.

2 Answers

Tkinter widgets are classes.

But in the above text example, a website mentioned that A text widget is created by using the Text() method.

That website is incorrect. They are classes, and you can verify that by looking in the source code for tkinter where you'll see class definitions for every one of the widgets (Text, Label, Frame, etc).

For example, the first part of the text widget looks like this (taken from the __init__.py file of tkinter):

class Text(Widget, XView, YView):
    """Text widget which can display text in various forms."""
    def __init__(self, master=None, cnf={}, **kw):
        """Construct a text widget with the parent MASTER.

        STANDARD OPTIONS

            background, borderwidth, cursor,
            exportselection, font, foreground,
            highlightbackground, highlightcolor,
            highlightthickness, insertbackground,
            insertborderwidth, insertofftime,
            insertontime, insertwidth, padx, pady,
            relief, selectbackground,
            selectborderwidth, selectforeground,
            setgrid, takefocus,
            xscrollcommand, yscrollcommand,

        WIDGET-SPECIFIC OPTIONS

            autoseparators, height, maxundo,
            spacing1, spacing2, spacing3,
            state, tabs, undo, width, wrap,

        """
        Widget.__init__(self, master, 'text', cnf, kw)

The inspect module might help you clear up your confusion.

In [37]: import inspect

In [38]: from tkinter import Text

In [39]: T = Text()

In [40]: inspect.isclass(Text)
Out[40]: True

In [41]: inspect.ismethod(Text)
Out[41]: False

In [42]: inspect.ismethod(T.pack)
Out[42]: True
Related