Simple demo code to show how to use tkinter with classes

This is the place to post any code that you want to share with the community. Only completed scripts should be posted here.
Note: posts here are not necessarily endorsed by the community, and may represent amateur or even bad practices.

Simple demo code to show how to use tkinter with classes

Postby Ofnuts » Sat Jul 09, 2016 8:47 am

Look Ma, no globals!

Code: Select all
#! /usr/bin/python3

import tkinter as tk

# Sample demo code to show how to efficiently use tkinter with classes

# This is the class that represent a window, in more complex designs you can also
# use such classes for smaller elements (panels, etc...)

class MainWindow(tk.Frame):
    def __init__ (self,mainwin,title):
        self.mainwin=mainwin
        self.mainwin.title(title)
        super().__init__(self.mainwin)

        self.grid(rows=5, columns=3)
       
        # Tkinter variables to get the contents of the widgets.
        # These variables are attributes of this class
        self.lengthVar=tk.IntVar()       
        self.enableVar=tk.BooleanVar(False)
       
        # Three widgets to interact with the user. These are all attributes of this class
        # Note that the callbacks we use with them are methods of this very class, and,
        # more accurately, method of this very instance...
        self.textWidget=tk.Entry(self, validate='key',vcmd=(self.register(self.textChanged),'%P'))
        self.lengthDisplay=tk.Label(self,textvariable=self.lengthVar)
        self.enableButton=tk.Checkbutton(self, text="Enable text entry", variable=self.enableVar, onvalue=True, offvalue=False, command=self.buttonChanged)
       
        self.textWidget.grid(row=2, column=2, padx=5, pady=5)
        self.lengthDisplay.grid(row=3, column=2, padx=5, pady=5)
        self.enableButton.grid(row=4, column=2, padx=5, pady=5)
        self.pack()

        self.textWidget.insert(0,'Enable this with checkbox...')
        self.textWidget.config(state=tk.NORMAL if self.enableVar.get() else tk.DISABLED)
        self.lengthVar.set('*****')

        return

    # Called when the button is clicked. Note that it is called with a 'self' parameter,
    # which is indeed a reference to the MainWindow instance that created that button widget.
    # This means this 'self' can be used to reference self.buttonWidget (the widget
    # that changed) but also its related variable (self.enableVar) and its sibling widgets (self.textWidget)
    def buttonChanged(self):
        print('In buttonChanged()...')
        self.textWidget.config(state=tk.NORMAL if self.enableVar.get() else tk.DISABLED)

    # Called when the text field contents change. It is called with a 'self' parameter,
    # which is indeed a reference to the MainWindow instance that created that text widget.
    # This means this 'self' can be used to reference self.textWidget (the widget
    # that changed) but also its sibling widgets and variables
    # (self.lengthVar)
    def textChanged(self,final):
        print('In textChanged()...: %s' % final)
        self.lengthVar.set(len(final))
        return True

def main():
    # Create the apps main window
    root=tk.Tk()
    # Populate it
    mw1=MainWindow(root,'First window')
    # Create a second top level window, and make it work the same way
    mw2=MainWindow(tk.Toplevel(root),'Second window')
    tk.mainloop()

main()
This forum has been moved to http://python-forum.io/. See you there.
User avatar
Ofnuts
 
Posts: 2659
Joined: Thu May 14, 2015 9:46 am
Location: Paris, France, EU, Earth, Solar system, Milky Way, Local Cluster, Universe #32987440940987

Return to Completed Scripts

Who is online

Users browsing this forum: No registered users and 2 guests