How to do it...

Towards the top of our Python GUI module, just below the import statements, we create several classes:

import tkinter as tk 
from tkinter import ttk
from tkinter import scrolledtext
from tkinter import Menu

class ButtonFactory():
def createButton(self, type_):
return buttonTypes[type_]()

class ButtonBase():
relief ='flat'
foreground ='white'
def getButtonConfig(self):
return self.relief, self.foreground

class ButtonRidge(ButtonBase):
relief ='ridge'
foreground ='red'

class ButtonSunken(ButtonBase):
relief ='sunken'
foreground ='blue'

class ButtonGroove(ButtonBase):
relief ='groove'
foreground ='green'

buttonTypes = [ButtonRidge, ButtonSunken, ButtonGroove]

class OOP():
def __init__(self):
self.win = tk.Tk()
self.win.title("Python GUI")
self.createWidgets()

We create a base class that our different button style classes inherit from and in which each of them overrides the relief and foreground configuration properties. All subclasses inherit the getButtonConfig method from this base class. This method returns a tuple.

We also create a button factory class and a list that holds the names of our button subclasses. We name the list buttonTypes, as our factory will create different types of buttons.

Further down in the module, we create the button widgets, using the same buttonTypes list:

    def createButtons(self): 

factory = ButtonFactory()

# Button 1
rel = factory.createButton(0).getButtonConfig()[0]
fg = factory.createButton(0).getButtonConfig()[1]
action = tk.Button(self.monty, text="Button "+str(0+1),
relief=rel, foreground=fg)
action.grid(column=0, row=1)

# Button 2
rel = factory.createButton(1).getButtonConfig()[0]
fg = factory.createButton(1).getButtonConfig()[1]
action = tk.Button(self.monty, text="Button "+str(1+1),
relief=rel, foreground=fg)
action.grid(column=1, row=1)

# Button 3
rel = factory.createButton(2).getButtonConfig()[0]
fg = factory.createButton(2).getButtonConfig()[1]
action = tk.Button(self.monty, text="Button "+str(2+1),
relief=rel, foreground=fg)
action.grid(column=2, row=1)

First, we create an instance of the button factory and then we use our factory to create our buttons.

The items in the buttonTypes list are the names of our subclasses.

We invoke the createButton method and then immediately call the getButtonConfig method of the base class and retrieve the configuration properties using dot notation.

When we run the entire code, we get the following Python tkinter GUI:

GUI_DesignPattern.py

We can see that our Python GUI factory did indeed create different buttons, each having a different style. They differ in the color of their text and in their relief property.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.136.119