官术网_书友最值得收藏!

Setting up the GUI in OOP

The text editor we developed in the previous chapter was implemented in procedural code. Although it offered some benefits for quick coding, it had some typical limitations:

  • We started encountering global variables
  • The function definitions needed to be defined above the code that called them
  • Most importantly, the code was not reusable

Therefore, we need some way to ensure that our code is reusable. This is why programmers prefer to use object-oriented programming (OOP) to organize their code into classes.

OOP is a programming paradigm that shifts the focus onto the objects we want to manipulate rather than the logic required to manipulate them. This is in contrast to procedural programming, which views a program as a logical procedure that takes input, processes it, and produces some output. 

OOP provides several benefits, such as data abstraction, encapsulation, inheritance, and polymorphism. In addition, OOP provides a clear modular structure for programs. Code modification and maintenance are easy, as new objects can be created without modifying the existing ones.

Let's build our drum program using OOP to illustrate some of these features. An indicative OOP structure for our drum program could be as follows (code 3.01.py):

from tkinter import Tk

PROGRAM_NAME = ' Explosion Drum Machine '

class DrumMachine:

def __init__(self, root):
self.root = root
self.root.title(PROGRAM_NAME)

if __name__ == '__main__':
root = Tk()
DrumMachine(root)
root.mainloop()

The description of the code is as follows:

  • We create a class structure called DrumMachine and initialize the Toplevel window passed as an argument to it
  • If the script is run as a standalone program, that is, if __name__ == '__main__', a new Tk() root object is created and the root window is passed as an argument to the DrumMachine object
  • We then initiate an object from the DrumMachine class to get a Toplevel window

Now that we have our Toplevel window ready, let's stop adding any more visual elements and think about something that is critical to how well our program will eventually turn out to be. Let's spend some time finalizing the data structure for our program.

主站蜘蛛池模板: 桐庐县| 花莲县| 苏尼特左旗| 浠水县| 辽阳市| 齐河县| 介休市| 岚皋县| 大宁县| 钦州市| 新巴尔虎左旗| 天气| 庄浪县| 建阳市| 元谋县| 莆田市| 布拖县| 开原市| 荥经县| 乌什县| 大丰市| 高唐县| 盐源县| 罗定市| 库尔勒市| 岳阳县| 永昌县| 长治市| 万全县| 明水县| 盐城市| 遵义县| 宜川县| 吴旗县| 临澧县| 寿光市| 临汾市| 宝山区| 荣昌县| 马尔康县| 宾阳县|