Hướng dẫn python countdown timer in background - đồng hồ đếm ngược python trong nền

Sử dụng mô -đun # Import the time module import time from tkinter import * import multiprocessing from tkinter import ttk, messagebox from playsound import playsound from threading import * 2 để chạy nhiều luồng cùng một lúc

Bạn có thể sử dụng mô -đun Python


# Import the time module
import time
from tkinter import *
import multiprocessing
from tkinter import ttk, messagebox
from playsound import playsound
from threading import *

2 để thực hiện hai điều xảy ra cùng một lúc, do đó cho phép người dùng trả lời trong khi bộ hẹn giờ đánh dấu.

Một số mã ví dụ sử dụng điều này:

from threading import Thread
from time import sleep
import sys

def timer():
    for i in range(45):
        sleep(1)   #waits 45 seconds
    sys.exit() #stops program after timer runs out, you could also have it print something or keep the user from attempting to answer any longer

def question():
    answer = input("foo?")

t1 = Thread(target=timer)
t2 = Thread(target=question)
t1.start() #Calls first function
t2.start() #Calls second function to run at same time

Nó không hoàn hảo, nhưng mã này sẽ bắt đầu hai chủ đề khác nhau, một chủ đề hỏi một câu hỏi và một lần hết thời gian 45 giây trước khi chấm dứt chương trình. Thông tin thêm về


# Import the time module
import time
from tkinter import *
import multiprocessing
from tkinter import ttk, messagebox
from playsound import playsound
from threading import *

2 có thể được tìm thấy trong các tài liệu. Hy vọng điều này sẽ giúp với dự án của bạn!

Hướng dẫn python countdown timer in background - đồng hồ đếm ngược python trong nền

Giới thiệu

Bộ đếm thời gian đếm ngược được sử dụng để đo lường liệu một nhiệm vụ đã hoàn thành trước khoảng thời gian hay đo thời gian một nhiệm vụ đã hoàn thành. Có nhiều ví dụ thực tế nơi nó được sử dụng. Ví dụ, kỳ thi trực tuyến, trong thể thao, v.v.

Trong hướng dẫn này, chúng tôi sẽ tạo một bộ đếm thời gian đếm ngược trong Python. Chúng tôi sẽ sử dụng thư viện Tkinter để biến nó thành một dự án GUI.Countdown Timer in Python. We will use the Tkinter library to make it a GUI project.

Bạn sẽ có thể thực hiện các nhiệm vụ sau:

☛set thời gian

☛ Bắt đầu hoặc tiếp tục thời gian

Tính thời gian đếm ngược (không có chức năng ngủ)Pause the Countdown Time (without sleep function)

Khi thời gian còn lại kết thúc, một bản nhạc sẽ phát trong nền.a music will play in the background.

Tìm thêm các dự án liên quan đến Python Tkinter.

Ứng dụng 👉medites in Python Tkinter: Thực hành thở sâu

Tốc độ đánh máy của bạn với Python - Dự án Tkinter & NBSP; 

Tạo một đồng hồ báo thức nâng cao bằng cách sử dụng Python Tkinter

Trình chuyển đổi phác thảo bằng bút chì trong Python - Dự án Tkinter

Các chi tiết dự án

Đầu tiên, bạn phải đặt thời gian thông qua ComboBox, sau đó nhấn nút 'Đặt'. Khi nhấn nút 'Đặt', hai nút nữa (nút 'Bắt ​​đầu' và nút 'Tạm dừng') sẽ xuất hiện ở phía bên phải. & nbsp;Combobox, then press the 'Set' button. When the 'Set' button is pressed, two more buttons(the 'Start' button and 'Pause' button) will appear on the right side.  

Bạn có thể bắt đầu và tạm dừng bộ hẹn giờ như nhu cầu của bạn. Tính năng tạm dừng làm cho bộ hẹn giờ đáng tin cậy hơn.. The pause feature makes the Timer more reliable.

Nếu bạn nhấn nút 'Bắt ​​đầu', thời gian còn lại sẽ hiển thị trên màn hình và mỗi giây sẽ giảm đi 1. Khi thời gian còn lại về 0, một thông báo sẽ được bật lên bằng âm nhạc, phát ở chế độ nền.'Start' button, the remaining time will show on the screen and every second will decrease by 1. When the remaining time reaches zero, a notification will be popped up with music, playing in the background.

Hãy xem toàn bộ video để biết thời gian đếm ngược này thực sự hoạt động như thế nào.

Lưu ý quan trọng

Trong dự án này, tôi đã sử dụng mô -đun Playsound để phát tệp MP3 để thông báo. Trong chương trình chính, bạn sẽ thấy một tệp nhạc được thêm như thế này: "Nhạc chuông/lãng mạn.mp3". & NBSP;playsound module to play an mp3 file for the notification. In the main program, you'll see a music file added like this: "Ringtones/romantic.mp3". 

Cần phải trình bày tệp "lãng mạn.mp3" này trong thư mục "Nhạc chuông" trong thư mục chính nơi đặt tệp chương trình. Bạn cũng có thể sử dụng một tệp nhạc khác; Chỉ cần đề cập đến con đường đúng cách trong chương trình.romantic.mp3" file in the "Ringtones" folder in the main directory where the program file is situated. You can also use another music file; just need to mention the path properly in the program.

Yêu cầu và cài đặt

🔹tkinter: Pip Cài đặt TK

🔹playsound: Pip Cài đặt Playsound

Nhập các mô -đun

Chúng ta hãy tạo một thư mục riêng 'đếm ngược' và khai báo một tệp python ở đó với tên này: 'Countdown.py'. Bạn cần tạo thêm một thư mục 'Nhạc chuông' trong thư mục 'đếm ngược' để lưu trữ các tệp nhạc hoặc nhạc chuông ở đó.CountDown' and declare a python file there with this name: 'CountDown.py'. You need to create one more folder 'Ringtones' under the 'Countdown' directory for storing music files or ringtones there.

Bây giờ bắt đầu viết mã của bạn bằng cách nhập các mô -đun này.


# Import the time module
import time
from tkinter import *
import multiprocessing
from tkinter import ttk, messagebox
from playsound import playsound
from threading import *

Tuyên bố danh sách giờ và phút

Ở đây, hai danh sách Python này chứa danh sách giờ và phút sẽ được sử dụng trong chương trình sắp tới.hours and minutes list which are gonna used in the upcoming program.


# Hour list
hour_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 
15, 16, 17, 18, 19, 20, 21, 22, 23, 24]

# Minute List
min_sec_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 
]

Tuyên bố lớp 'đếm ngược'

Ở đây tất cả các tiện ích Tkinter (nhãn, nút, hộp kết hợp, v.v.) đã được khai báo.


# Creating a CounDown Class
class CountDown:
    def __init__(self, root):
        self.window = root
        self.window.geometry("480x320+0+0")
        self.window.title('CountDown Timer')
        # Tkinter window background color
        self.window.configure(bg='gray35')
        # Fixing the Window length constant
        self.window.resizable(width = False, height = False)

        # Declaring a variable to pause the countdown time
        self.pause = False

        # The Start and Pause buttons are placed
        # inside this frame
        self.button_frame = Frame(self.window, bg="gray35", \
        width=240, height=40)
        self.button_frame.place(x=230, y=150)
        # This frame is used to show the countdown time label
        self.time_frame = Frame(self.window, bg="gray35", \
        width=480, height=120).place(x=0, y=210)

        # Tkinter Labels
        time_label = Label(self.window, text="Set Time", 
        font=("times new roman",20, "bold"), bg='gray35',fg='yellow')
        time_label.place(x=180, y=30)

        hour_label = Label(self.window, text="Hour", 
        font=("times new roman",15), bg='gray35', fg='white')
        hour_label.place(x=50, y=70)

        minute_label = Label(self.window, text="Minute", 
        font=("times new roman",15), bg='gray35', fg='white')
        minute_label.place(x=200, y=70)

        second_label = Label(self.window, text="Second", 
        font=("times new roman",15), bg='gray35', fg='white')
        second_label.place(x=350, y=70)
        # ===========================================

        # Tkinter Comboboxes
        # Combobox for hours
        self.hour = IntVar()
        self.hour_combobox = ttk.Combobox(self.window, width=8, 
        height=10, textvariable=self.hour, 
        font=("times new roman",15))
        self.hour_combobox['values'] = hour_list
        self.hour_combobox.current(0)
        self.hour_combobox.place(x=50,y=110)

        # Combobox for minutes
        self.minute = IntVar()
        self.minute_combobox = ttk.Combobox(self.window, width=8, 
        height=10, textvariable=self.minute, 
        font=("times new roman",15))
        self.minute_combobox['values'] = min_sec_list
        self.minute_combobox.current(0)
        self.minute_combobox.place(x=200,y=110)

        # Combobox for seconds
        self.second = IntVar()
        self.second_combobox = ttk.Combobox(self.window, width=8, 
        height=10, textvariable=self.second, 
        font=("times new roman",15))
        self.second_combobox['values'] = min_sec_list
        self.second_combobox.current(0)
        self.second_combobox.place(x=350,y=110)
        # ===========================================

        # Tkinter Buttons
        # Cancel button
        cancel_button = Button(self.window, text='Cancel', 
        font=('Helvetica',12), bg="white", fg="black", 
        command=self.Cancel)
        cancel_button.place(x=70, y=150)

        # Set Time Button
        # When the user will press this button
        # the 'Start' and 'Pause' button will
        # show inside the 'self.button_frame' frame
        set_button = Button(self.window, text='Set', 
        font=('Helvetica',12), bg="white", fg="black", 
        command=self.Get_Time)
        set_button.place(x=160, y=150)

Chức năng hủy bỏ

Khi nhấn nút Hủy, chức năng này nhận được một cuộc gọi. Nó dừng chương trình và phá hủy cửa sổ GUI.Cancel Button is pressed, this function gets a call. It stops the program and destroys the GUI window.


# It will destroy the window
    def Cancel(self):
        self.pause = True
        self.window.destroy()

Nhận thời gian từ người dùng

Khi nhấn nút 'SET', hàm 'get_time ()' này sẽ mất thời gian do người dùng đặt. Nếu người dùng cố gắng đặt giá trị mặc định (0: 0: 0, hãy xem dòng màu vàng), chương trình sẽ hiển thị thông báo cảnh báo trên màn hình để đặt thời gian chính xác.'Set' Button is pressed, this 'Get_Time()' function takes the time set by the user. If the users try to set the default value(0:0:0, see the yellow line), the program will show a warning message on the screen to set a correct time.

Sau khi nhấn nút 'Đặt', các nút 'Bắt ​​đầu' và 'Tạm dừng' xuất hiện ở phía bên phải cho phép người dùng bắt đầu hoặc tiếp tục và tạm dừng thời gian khi cần.'Set' Button, the 'Start' and 'Pause' buttons appear on the right side that allows the users to Start or Resume and Pause the time as their need.


    # When the set button is pressed, this
    # function gets called
    def Get_Time(self):
        self.time_display = Label(self.time_frame, 
        font=('Helvetica', 20 , "bold"), 
        bg = 'gray35', fg = 'yellow')
        self.time_display.place(x=130, y=210)

        try:
            # Total amount of time in seconds
            h = (int(self.hour_combobox.get())*3600)
            m = (int(self.minute_combobox.get())*60)
            s = (int(self.second_combobox.get()))
            self.time_left = h + m + s

            # If the user try to set the default time(0:0:0) then
            # a warning message will display
            if s == 0 and m == 0 and h == 0:
                messagebox.showwarning('Warning!',\
                'Please select a right time to set')
            else:
                # Start Button
                start_button = Button(self.button_frame, text='Start', 
                font=('Helvetica',12), bg="green", fg="white", 
                command=self.Threading)
                start_button.place(x=20, y=0)

                # Pause Button
                pause_button = Button(self.button_frame, text='Pause', 
                font=('Helvetica',12), bg="red", fg="white",
                command=self.pause_time)
                pause_button.place(x=100, y=0)
        except Exception as es:
            messagebox.showerror("Error!", \
            f"Error due to {es}")

Tạo một chủ đề khác

Bây giờ tạo một chủ đề khác để xử lý các nhiệm vụ này:

1. Hiển thị thời gian còn lại

2. Xử lý bắt đầu và tạm dừng hoàn hảo.Handling Start and Pause function perfectly.

Nó sẽ giúp chạy bộ đếm thời gian đếm ngược một cách trơn tru.CountDown Timer Smoothly.


    # Creating a thread to run the show_time function
    def Threading(self):
        # Killing a thread through "daemon=True" isn't a good idea
        self.x = Thread(target=self.start_time, daemon=True)
        self.x.start()

Màn hình rõ ràng

Nhìn vào lớp 'đếm ngược' (đường màu vàng); Tôi đã thêm một khung có tên 'Nút_Frame' ở đó cho các nút bắt đầu và tạm dừng. Khi chức năng này được gọi, nó chỉ đơn giản là xóa tất cả các tiện ích (chỉ bắt đầu và tạm dừng các nút) có mặt ở đó.CountDown' class (yellow lines); I've added a frame named 'button_frame' there for the Start and Pause buttons. When this function gets called, it simply clears all the widgets (only Start and Pause buttons) present there.


# It wil clear all the widgets inside the
    # 'self.button_frame' frame(Start and Pause buttons)
    def Clear_Screen(self):
        for widget in self.button_frame.winfo_children():
            widget.destroy()

Hàm bắt đầu

Xem, ngay từ đầu tôi đã đặt self.Apause = false. Trong mỗi lần lặp của vòng lặp trong khi mã kiểm tra xem trạng thái của bản thân có đúng hay không. Khi nó đúng (khi nhấn nút tạm dừng), vòng lặp trong khi bị hỏng.self.pause = False. In every iteration of the while loop the code checks if the status of self.pause is True or not. When it's True (when the pause button is pressed), the while loop breaks.

Hướng dẫn python countdown timer in background - đồng hồ đếm ngược python trong nền


# When the Start button will be pressed then,
    # this "show_time" function will get called.
    def start_time(self):
        self.pause = False
        while self.time_left > 0:
            mins, secs = divmod(self.time_left, 60)

            hours = 0
            if mins > 60:
                # hour minute
                hours, mins = divmod(mins, 60)

            self.time_display.config(text=f"Time Left: {hours}: {mins}: {secs}")
            self.time_display.update()
            # sleep function: for 1 second
            time.sleep(1)
            self.time_left = self.time_left -1
            # When the time is over, a piece of music will
            # play in the background
            if self.time_left <= 0:
                process = multiprocessing.Process(target=playsound, 
                args=('Ringtones/romantic.mp3',))
                process.start()
                messagebox.showinfo('Time Over','Please ENTER to stop playing')
                process.terminate()
                # Clearing the 'self.button_frame' frame
                self.Clear_Screen()
            # if the pause button is pressed,
            # the while loop will break
            if self.pause == True:
                break

Hàm tạm dừng

Hãy nhìn xem, ở vị trí đầu tiên của trạng thái của bản thân được đặt đúng. Nó tạm dừng thời gian từ việc giảm trong vòng lặp trong khi chức năng bắt đầu (hãy nhớ rằng, nó xảy ra khi vòng lặp bị hỏng). Sau đó, nó chỉ hiển thị thời gian còn lại trên màn hình ở điều kiện tạm dừng.self.pause is set True. It pauses the time from reducing in the while loop at the Start function(remember, it happens when the while loop breaks). Then it only displays the remaining time on the screen at the pause condition.

Hướng dẫn python countdown timer in background - đồng hồ đếm ngược python trong nền


    def pause_time(self):
        self.pause = True

        mins, secs = divmod(self.time_left, 60)
        hours = 0
        if mins > 60:
            # hour minute
            hours, mins = divmod(mins, 60)

        self.time_display.config(text=f"Time Left: {hours}: {mins}: {secs}")
        self.time_display.update()

Chức năng chính


# Import the time module
import time
from tkinter import *
import multiprocessing
from tkinter import ttk, messagebox
from playsound import playsound
from threading import *

0

Mã đầy đủ

Đây là mã đầy đủ cho sự thuận tiện của bạn.


# Import the time module
import time
from tkinter import *
import multiprocessing
from tkinter import ttk, messagebox
from playsound import playsound
from threading import *

1

Tải xuống mã nguồn

Tải xuống mã nguồn từ trang GitHub của tôi (https://github.com/subhankar-rakshit) thông qua nút tải xuống.

☛visit cũng: Xây dựng ứng dụng người xem hình ảnh bằng Python Tkinter: Build an Image Viewer Application using Python Tkinter

Bản tóm tắt

Trong hướng dẫn này, chúng tôi xây dựng một bộ đếm thời gian đếm ngược trong Python. Chúng tôi đã thêm các tính năng bắt đầu và tạm dừng cho bộ đếm thời gian này. Người dùng có thể bắt đầu hoặc tiếp tục hẹn giờ và tạm dừng nó.Countdown Timer in Python. We added Start and Pause features to this Timer. The users can start or resume the timer and pause it too.

Nó rất dễ sử dụng vì giao diện đồ họa được quản lý bởi Thư viện Python Tkinter. Hãy sử dụng nó và cho tôi biết nó hoạt động như thế nào.graphical interface which is managed by Python Tkinter library. Do use it and let me know how its performing.

Nếu bạn gặp khó khăn trong việc hiểu ở đâu đó, hãy chắc chắn để lại nhận xét của bạn trong phần bình luận bên dưới. Bạn sẽ nhận được hồi âm sớm.

Cảm ơn vì đã đọc! 💙

Pyseek

Làm thế nào để bạn thực hiện một bộ đếm thời gian đếm ngược trong Python?

Thực hiện theo các bước dưới đây để tạo bộ đếm thời gian đếm ngược:..
Bước 1: Nhập mô -đun thời gian ..
Bước 2: Sau đó, yêu cầu người dùng nhập chiều dài đếm ngược tính bằng giây ..
Bước 3: Giá trị này được gửi dưới dạng tham số 'T' đến Đá danh chức năng do người dùng xác định (). ....
Bước 4: Trong chức năng này, vòng lặp thời gian chạy cho đến khi thời gian trở thành 0 ..

Làm thế nào để bạn tạm dừng sơ yếu lý lịch và đếm thời gian đếm ngược trong Python?

Hãy xem xét thứ tự thực hiện các tuyên bố của bạn ...
Bạn tạo đối tượng đếm ngược ..
Bạn chạy số đếm.Phương pháp chạy ..
Bạn ngủ trong 3 giây ..
Bạn tạm dừng bằng phương pháp đếm.Alause ..

Có hẹn giờ trong Python không?

Một bộ đếm thời gian trong Python là một chương trình theo dõi thời gian.Các nhà phát triển Python có thể tạo bộ hẹn giờ với sự trợ giúp của các mô -đun thời gian của Python.Có hai loại hẹn giờ cơ bản: bộ hẹn giờ đếm và những loại đếm ngược.

Làm thế nào để bạn chạy một chức năng trong Python cứ sau 5 giây?

Hàm Mode Sleep () cho phép bạn ngủ mã của mình trong một khoảng thời gian xác định tính bằng giây.Để chạy mã cứ sau 5 giây trong Python, bạn có thể sử dụng một vòng lặp và vượt qua '5' trong 5 giây để ngủ ().use a loop and pass '5' for 5 seconds to sleep().