This article is published simultaneously on my wechat official account. You can follow it by scanning the QR code at the bottom of the article or searching the Geek navigation on wechat. The article will be updated every weekday.

A profile,

Our three-dimensional world is not like a four-dimensional world where time can be controlled at will. Time is really past, I have to say that time is a little fast ah, some of the memories of high school fragments will emerge in my mind. In high school class, some students want the teacher to ask more questions about themselves, and some students in the bottom but silently pray, hope not to ask him, and even some students think that the teacher asked him to make trouble with him. Looking back on it now, I wonder if I would scold myself “sharkdrop”. So today we use Python program to write a classroom roll call, using Python GUI programming, this is really very fair, not biased. Finally, I would like to say a word to you: please cherish the time.

Second, page building

We use the Tkinter module in Python, and we do three things roughly:

  • Random roll call
  • punishment
  • Log write

First of all, we will simply build the interface, the code is very simple:

import tkinter as tk


class LoveYou(a):

    # initialization
    def __init__(self):
        Step 1: Create the window
        self.window = tk.Tk()

        Step 2, name the window visualization
        self.window.title('Class Word test program')

        Step 3: Set the window size (length * width)
        self.window.geometry('600x400')

        self.text = tk.StringVar()  # create STR type
        self.count = tk.StringVar()

    def take(self):
        Return: ""
        pass

    def kill(self):
        Responsible for selecting different punishment times based on the day of the week :return: ""
        pass

    def main(self):
        Main function is responsible for drawing :return:"

        Draw filter information
        l2 = tk.Label(self.window, fg='red', textvariable=self.text, width=500, height=3)
        l2.config(font='Helvetica -%d bold' % 30)
        l2.pack()

        # Draw penalty message
        l3 = tk.Label(self.window, fg='red', textvariable=self.count, width=500, height=3)
        l3.config(font='Helvetica -%d bold' % 20)
        l3.pack()

        Draw the filter button
        btntake = tk.Button(self.window, text="Screening", width=15, height=2, command=self.take)
        btntake.pack()

        Draw the penalty button
        btnkill = tk.Button(self.window, text="Punishment", width=15, height=2, command=self.kill)
        btnkill.pack()

        # enter the loop
        self.window.mainloop()


if __name__ == '__main__':
    loveyou = LoveYou()
    loveyou.main()

Copy the code

take
kill

Third, data acquisition

In class, we usually have a list of class members (xxx.xlsx). When we initialize the program, we read local data into the program. Let’s create a table locally to write some fake data:

xlrd

pip install xlrd
Copy the code

Let’s write a function to read:

    def read_data(self):
        Data read :return: ""
        workbook = xlrd.open_workbook('1801.xlsx')

        sheet1 = workbook.sheet_by_index(0)  The # sheet index starts at 0

        data = sheet1.col_values(0)  Read the first column

        # [' table 1 ', 'name', 'wang', 'Lao wang', 'xiao Ming', 'red', 'green', 'xiaoqing', 'Chen', 'xiao zhao', 'wang', 'Ms. Li', 'note:', 'little weeks',' xiao wu ', 'money', 'miniature schnauzer', 'small three', 'four', 'Little Five ',' Little six ']

        data.pop(0)  Drop table 1
        data.pop(0)  # Remove the name

        return data
Copy the code

The data returned in this function is the list of classmates read locally.

Four, name implementation

We set a total of random times, such as 50 times, until the final random out of the students as the result. The logic is as follows:

    def take(self):
        Return: ""

        for s in range(50) :"Slow down for the next few seconds to create tension."
            desc = ' '
            if s == 47:
                time.sleep(0.5)
            elif s == 48:
                time.sleep(0.6)
            elif s == 48:
                time.sleep(0.7)
            elif s == 49:
                time.sleep(0.9)
            else:
                time.sleep(0.1)

            classes = random.sample(self.data, 2)
            desc += "Yo, you have been chosen by God :%s\n" % classes[0]
            desc += "Yo, you look good too :%s\n" % classes[1]

            self.text.set(desc)  # Set content
            self.window.update()  # Screen update
Copy the code

Here is the dynamic diagram:

Realization of punishment

According to Monday to Friday, the amount of punishment is different every day. Let’s copy the punishment method temporarily.

  def kill(self):
        Responsible for selecting different punishment times based on the day of the week :return: ""

        if self.day == 1:
            count = random.randint(50.100)
            kill_desc = "God rewarded your team %d times." % (count)

        elif self.day == 2:
            count = random.randint(50.120)
            kill_desc = "God rewarded your team %d times." % (count)
            self.count.set(kill_desc)
        elif self.day == 3:
            count = random.randint(50.140)
            kill_desc = "God rewarded your team %d times." % (count)
        elif self.day == 4:
            count = random.randint(50.160)
            kill_desc = "God rewarded your team %d times." % (count)
            self.count.set(kill_desc)
        elif self.day == 5:
            count = random.randint(50.180)
            kill_desc = "God rewarded your team %d times." % (count)
        else:
            kill_desc = 'No questions for the weekend.'

        self.count.set(kill_desc)  # Set content
        self.window.update()  # Screen update
Copy the code

When we click on the filter, click on the punishment, there is a penalty write times.

Six, log implementation

The main purpose of the log is to record who asked questions, when they were asked, and the number of times they were punished. We all need to write this information to the local, otherwise the next day the teacher forgot who to test, students do not admit to ask me, so the log function is a must. Savedesc is called when the final questioner is confirmed and savecount is called when the punishment button is clicked


    def savedesc(self, desc):
        Write the selected person to the log :param desc: :return:
        with open('log.txt'.'a', encoding='utf-8') as f:
            f.write(self.gettime() + "\n" + desc)

    def savecount(self, count):
        Param count: :return: ""
        with open('log.txt'.'a', encoding='utf-8') as f:
            f.write(str(count) + '\n')
            f.write('--------------------------------\n')

Copy the code

The local file format is as follows:

Seven, other

That’s the basic function. I added some hints on the interface. Like today’s date, class size and so on.

import tkinter as tk

import xlrd

import time

import random

import datetime


class LoveYou(a):

    # initialization
    def __init__(self):
        Step 1: Create the window
        self.window = tk.Tk()

        Step 2, name the window visualization
        self.window.title('Class Word test program')

        Step 3: Set the window size (length * width)
        self.window.geometry('600x400')

        self.text = tk.StringVar()  # create STR type
        self.count = tk.StringVar()

        self.data = self.read_data()

        Get the day of the week
        d = datetime.datetime.now()
        self.day = d.weekday() + 1

    def read_data(self):
        Data read :return: ""
        workbook = xlrd.open_workbook('1801.xlsx')

        sheet1 = workbook.sheet_by_index(0)  The # sheet index starts at 0

        data = list(sheet1.col_values(0))  Read the first column

        # [' table 1 ', 'name', 'wang', 'Lao wang', 'xiao Ming', 'red', 'green', 'xiaoqing', 'Chen', 'xiao zhao', 'wang', 'Ms. Li', 'note:', 'little weeks',' xiao wu ', 'money', 'miniature schnauzer', 'small three', 'four', 'Little Five ',' Little six ']

        data.pop(0)  Drop table 1
        data.pop(0)  # Remove the name

        return data

    def take(self):
        Return: ""

        for s in range(50) :"Slow down for the next few seconds to create tension."
            desc = ' '
            if s == 47:
                time.sleep(0.5)
            elif s == 48:
                time.sleep(0.6)
            elif s == 48:
                time.sleep(0.7)
            elif s == 49:
                time.sleep(0.9)
            else:
                time.sleep(0.1)

            classes = random.sample(self.data, 2)
            desc += "Yo, you have been chosen by God :%s\n" % classes[0]
            desc += "Yo, you look good too :%s\n" % classes[1]

            if s == 49:
                self.savedesc(desc)  Write to log
            self.text.set(desc)  # Set content
            self.window.update()  # Screen update

    def kill(self):
        Responsible for selecting different punishment times based on the day of the week :return: ""

        if self.day == 1:
            count = random.randint(50.100)
            kill_desc = "God rewarded your team %d times." % (count)

        elif self.day == 2:
            count = random.randint(50.120)
            kill_desc = "God rewarded your team %d times." % (count)
            self.count.set(kill_desc)
        elif self.day == 3:
            count = random.randint(50.140)
            kill_desc = "God rewarded your team %d times." % (count)
        elif self.day == 4:
            count = random.randint(50.160)
            kill_desc = "God rewarded your team %d times." % (count)
            self.count.set(kill_desc)
        elif self.day == 5:
            count = random.randint(50.180)
            kill_desc = "God rewarded your team %d times." % (count)
        else:
            kill_desc = 'No questions for the weekend.'

        self.count.set(kill_desc)  # Set content
        self.window.update()  # Screen update

        self.savecount(kill_desc)  Write to log


    def gettime(self):
        Format time :return: ""
        return time.strftime('%Y-%m-%d', time.localtime(time.time())) + "  星期" + str(self.day)


    def savedesc(self, desc):
        Write the selected person to the log :param desc: :return:
        with open('log.txt'.'a', encoding='utf-8') as f:
            f.write(self.gettime() + "\n" + desc)

    def savecount(self, count):
        Param count: :return: ""
        with open('log.txt'.'a', encoding='utf-8') as f:
            f.write(str(count) + '\n')
            f.write('--------------------------------\n')

    def main(self):
        Main function is responsible for drawing :return:"

        # draw date, class size, etc
        now = time.strftime('%Y-%m-%d', time.localtime(time.time())) + "  星期" + str(self.day)
        now += "\n Total class size :%s" % str(len(self.data))
        now += "\n is under reasonable calculation \n"

        l1 = tk.Label(self.window, fg='red', text=now, width=500, height=5)
        l1.config(font='Helvetica -%d bold' % 15)
        l1.pack()  # Placement tag

        Draw filter information
        l2 = tk.Label(self.window, fg='red', textvariable=self.text, width=500, height=3)
        l2.config(font='Helvetica -%d bold' % 30)
        l2.pack()

        # Draw penalty message
        l3 = tk.Label(self.window, fg='red', textvariable=self.count, width=500, height=3)
        l3.config(font='Helvetica -%d bold' % 20)
        l3.pack()

        Draw the filter button
        btntake = tk.Button(self.window, text="Screening", width=15, height=2, command=self.take)
        btntake.pack()

        Draw the penalty button
        btnkill = tk.Button(self.window, text="Punishment", width=15, height=2, command=self.kill)
        btnkill.pack()

        # enter the loop
        self.window.mainloop()


if __name__ == '__main__':
    loveyou = LoveYou()
    loveyou.main()

Copy the code

Eight, summary

This program is mainly for learning GUI programming, this function may not be too perfect. If you are interested, you can follow this idea to write a better program, so that each student love being asked questions. When you are working on your own, you might say: Teacher, question me again!

Welcome to pay attention to my public number, we learn together.