I tried to remodel the code of Python beginner (junior high school student) into object-oriented crunchy

We will have you re-appear in the Program made by Mr. K, a junior high school student. The execution result looks like this コメント 2019-11-17 160125.png When you press the button, the value will count up. The program that used tk for the first time is well done. I think it's good to be able to realize a program that works as expected.

Made by Mr. K


import tkinter as tk

count = 0

def dispLabel():
    global count
    count = count + 1
    lbl.configure(text = str(count) + "Pressed twice")


root = tk.Tk()
root.geometry("300x80")

lbl = tk.Label(text="Count button")
btn = tk.Button(text="Press", command = dispLabel)

lbl.pack()
btn.pack()
tk.mainloop()

However, the program that stores the counter value as a global variable and is like a model for beginners.

In an actual program, the processing content may be more complicated, or similar processing may occur many times. By introducing object-oriented programming, you can create programs efficiently. Mr. K's program only had a button that counts up the numbers, but assuming that other buttons will be added to this, I will try to modify it into an object-oriented program

With K's programming method, the problem with adding buttons is that it is necessary to add global variables such as count1 and count2 to the button addition. The process of displaying in TK and the process of counting up are integrated and not separated. It seems good to create an object to count and have a count variable inside this object.

class Counter():
    def __init__(self):
        self.count = 0
    
    def get_next_value(self):
        self.count +=1
        return str(self.count)

Initialize count with \ _ \ _ init__ () and count up every time you call get_next_value ().

I also made DownCounter and CounterAlphabet. The Application class is an object that displays buttons and labels and updates the display when the button is pressed. I tried to manage the Application class by referring to Explanation of Tcl / Tkcl / Tk.

import tkinter as tk
    
class Counter():
    def __init__(self):
        self.count = 0
    
    def get_next_value(self):
        self.count +=1
        return str(self.count)

class DownCounter(Counter):
    def __init__(self):
        self.count = 99
    
    def get_next_value(self):
        self.count -=1
        return str(self.count)

class CounterAlphabet(Counter):
    word_list = ["zero", "one", "two", "three"]
    def get_next_value(self):
        self.count +=1
        try:
            return self.word_list[self.count]
        except IndexError:
            return "many"

class Application(tk.Frame):
    def __init__(self, master):
        super().__init__(master)
        self.master = master
        self.master.geometry("300x160")
        self.pack() 
            
    def add_button(self, counter, label="Count button", msg="Pressed twice"):
        lbl = tk.Label(text=label)
        def update_label():
            str = counter.get_next_value()
            lbl.configure(text = str + msg )
        btn = tk.Button(text="Press", command = update_label)
        lbl.pack()
        btn.pack()
    
root = tk.Tk()
app = Application(root)
counter1 = Counter()
counter2 = DownCounter()
counter3 = CounterAlphabet()
app.add_button(counter1, "Count button")
app.add_button(counter2, "Countdown button","Times")
app.add_button(counter3, "Count button(English)"," times")
app.mainloop()

Execution result コメント 実行結果

Thank you, Mr. K, for providing the program.

Program received in the comments

Mr. shiracamus commented on a more sophisticated example. Please refer to the comment section. Further magical modifications are welcome.

Recommended Posts

I tried to remodel the code of Python beginner (junior high school student) into object-oriented crunchy
I tried to refactor the code of Python beginner (junior high school student)
I tried to get the authentication code of Qiita API with Python.
[Python] A junior high school student implemented Perceptron and tried to classify irises.
I tried to summarize the string operations of Python
Programming beginner (junior high school student) Optimize the created algorithm
I tried to find the entropy of the image with python
[Python] I tried to visualize the follow relationship of Twitter
I tried to divide the file into folders with Python
From zero knowledge of Python to making AI in the first grade of junior high school
I wrote the code to write the code of Brainf * ck in python
I tried to improve the efficiency of daily work with Python
(Python) I tried to analyze 1 million hands ~ I tried to estimate the number of AA ~
I tried to verify and analyze the acceleration of Python by Cython
I tried to streamline the standard role of new employees with Python
I tried to get the movie information of TMDb API with Python
I tried to touch the API of ebay
I tried to correct the keystone of the image
I tried to predict the price of ETF
I tried to vectorize the lyrics of Hinatazaka46!
[Python] I tried to judge the member image of the idol group using Keras
I tried to easily visualize the tweets of JAWS DAYS 2017 with Python + ELK
I tried to automate the 100 yen deposit of Rakuten horse racing (python / selenium)
I tried to automatically send the literature of the new coronavirus to LINE with Python
python beginners tried to predict the number of criminals
I tried to graph the packages installed in Python
I tried to summarize how to use matplotlib of python
I tried to summarize the basic form of GPLVM
I tried to touch the CSV file with Python
I tried to put out the frequent word ranking of LINE talk with Python
Python practice 100 knocks I tried to visualize the decision tree of Chapter 5 using graphviz
I tried to solve the soma cube with python
I tried to automate the article update of Livedoor blog with Python and selenium.
mong --I tried porting the code that randomly generates Docker container names to Python -
Python beginner (junior high school student) combination generation was diagonally above (combination generation by recursive processing)
I tried to put pytest into the actual battle
[Python] I tried to graph the top 10 eyeshadow rankings
I tried to visualize the spacha information of VTuber
I tried to erase the negative part of Meros
I tried to solve the problem with Python Vol.1
I felt that I ported the Python code to C ++ 98.
[Python] I tried to get Json of squid ring 2
I tried to compare the processing speed with dplyr of R and pandas of Python
I tried to classify the voices of voice actors
I tried running the sample code of the Ansible module
The 15th offline real-time I tried to solve the problem of how to write with python
How to write offline real time I tried to solve the problem of F02 with Python
I tried "Streamlit" which turns the Python code into a web application as it is
I tried to get the number of days of the month holidays (Saturdays, Sundays, and holidays) with python
I tried to create a Python script to get the value of a cell in Microsoft Excel
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
[Horse Racing] I tried to quantify the strength of racehorses
I tried "gamma correction" of the image with Python + OpenCV
I tried to simulate how the infection spreads with Python
I tried to get the location information of Odakyu Bus
I tried the accuracy of three Stirling's approximations in python
I tried to find the average of the sequence with TensorFlow
[Markov chain] I tried to read negative emotions into Python.
[Markov chain] I tried to read a quote into Python.
I tried to summarize the code often used in Pandas
The process of making Python code object-oriented and improving it