Here we are providing basic tutorial in Tkinter to use classes in Tkinter programs.

Consider this code

from tkinter import *

class CodeshotButtons:

    def __init__(self, master):
        frame = Frame(master)

        self.printButton = Button(frame, text="Print Message", command=self.printMessage)

        self.quitButton = Button(frame, text="Quit", command=frame.quit)

    def printMessage(self):
        print("Wow! this works")

root = Tk()
b = CodeshotButtons(root)

In above code, a class namely CodeshotButtons is being created, in that class a function __init__ is declared that is by default called when an object of the class is created. Two parameters self and master are passed to __init__ function, self is used to refer the object that is created i.e b in above case in the second last line of the code, also root is passed while creating the object b. This root is passed to the master of the__init__ function, hence in class, master will be acting as main GUI window.

In the class, two buttons are created printButton for printing and quitButton for quitting the GUI window. Both buttons are in a frame. A function printMessage is used to display the message.



On pressing the button printButton i.e Print Message, output will appear on command line window like this -


On pressing the button quitButton i.e Quit, output will appear on command line window like this -