Build a Python Tkinter Auto‑Learning Timer: GUI, Captcha, and Threaded Requests

This tutorial explains how to create a Python Tkinter desktop tool that automates login, captcha handling, and periodic study‑time submissions to an online learning platform using Requests, multithreading, and a state‑machine UI for reliable operation.

Dunmao Tech Hub
Dunmao Tech Hub
Dunmao Tech Hub
Build a Python Tkinter Auto‑Learning Timer: GUI, Captcha, and Threaded Requests

Overall Function Overview

Graphical Interface : Built with Tkinter; users input username, password, and captcha.

Captcha Retrieval & Refresh : Fetches captcha images from the server and displays them in the GUI.

Automatic Login : Submits credentials after Base64 encoding and validates the response.

Study‑Time Automation : A background thread periodically sends study‑time requests to the server.

Progress Display : Shows accumulated study time and target progress via a progress bar and labels.

Status Management : Implements a state‑machine to switch UI controls appropriately across different stages.

When the user logs in successfully and clicks “Start”, the program continuously posts study‑time data and updates the UI in real time.

Core Technology Stack

Tkinter : Standard Python GUI toolkit for rapid desktop tool development.

Requests : Popular HTTP library used to communicate with the learning platform.

Pillow (PIL) : Handles captcha image processing for display in Tkinter.

Multithreading + Queue : Uses threading.Thread and queue.Queue to perform asynchronous network requests without blocking the GUI.

State‑Machine Pattern : Centralises UI state changes via a set_ui_state method for clear logic.

Module Breakdown

1. GUI Construction

The main window is divided into three sections: a login area, a control area for setting request intervals and starting/stopping the timer, and a progress area that shows elapsed time and a progress bar.

login_frame = ttk.LabelFrame(main_frame, text="登录", padding="10")
self.username_entry = ttk.Entry(login_frame)
self.password_entry = ttk.Entry(login_frame)
self.captcha_entry = ttk.Entry(login_frame)
self.captcha_image_label = ttk.Label(login_frame)

The ttk.LabelFrame groups related widgets, making the interface intuitive.

2. Captcha Retrieval and Display

Captcha fetching runs in a dedicated thread to keep the UI responsive.

def _fetch_captcha_worker(self):
    response = self.session.get(self.URL_CAPTCHA, timeout=10)
    if response.status_code == 200:
        self.queue.put({"type": "captcha_image", "data": response.content})

After receiving the image bytes, Pillow converts them to ImageTk.PhotoImage for display:

image = Image.open(BytesIO(image_data))
self.captcha_photo = ImageTk.PhotoImage(image)
self.captcha_image_label.config(image=self.captcha_photo)

3. Login Logic

The password is Base64‑encoded before being sent to the server.

encoded_password = base64.b64encode(password.encode('utf-8')).decode('utf-8')
data = {
    'args[username]': username,
    'args[userpassword]': encoded_password,
    'args[randcode]': captcha,
    'userlogin': '1',
    'userhash': str(time.time())
}
response = self.session.post(self.URL_LOGIN, data=data, timeout=10)

Use requests.Session() to keep the session alive and avoid repeated logins.

Login results are passed to the main thread via a message queue to maintain Tkinter thread safety.

4. Automatic Study‑Time Logic

The core loop runs in worker_function, sending a study‑time request at regular intervals until the target minutes are reached or the user stops the process.

while not self.stop_event.is_set() and self.total_minutes < self.target_minutes:
    response = self.session.post(self.URL_STUDY, headers=headers, data=data, timeout=10)
    if response.status_code == 200:
        self.queue.put("success")

A threading.Event controls the thread’s termination, allowing immediate stop when the user clicks “Stop”.

5. UI State Machine

Different UI states (idle, logging in, logged in, running, stopped) enable or disable controls to prevent invalid actions.

states = {
    'IDLE': {...},      # before login
    'LOGGING_IN': {...},# during login
    'LOGGED_IN': {...},# after successful login
    'RUNNING': {...},   # while brushing time
    'STOPPED': {...},   # after stop
}

This pattern is clearer and more maintainable than scattering config(state=...) calls throughout the code.

Key Challenges and Solutions

Avoid GUI Blocking : All time‑consuming operations (network requests, loops) run in child threads, communicating with the main thread via queue.Queue. The main thread only updates the UI.

Captcha Loading Delay : The refresh button is disabled while a new captcha loads and re‑enabled once the image is ready.

Safe Exit : When the window closes, the program first sets stop_event to ensure the background thread terminates cleanly.

Conclusion

Designed a functional Tkinter GUI with clear layout.

Managed HTTP sessions and POST requests using Requests.

Combined multithreading and queues to solve Tkinter’s thread‑safety issues.

Applied a state‑machine pattern to simplify complex UI control management.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

GUIPythonAutomationrequestsTkinter
Dunmao Tech Hub
Written by

Dunmao Tech Hub

Sharing selected technical articles synced from CSDN. Follow us on CSDN: Dunmao.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.