Python Tkinter GUI is not stuck in running, multi -threading solution to the interface card death problem

tags: GUI visualization chapter  python  tkinter  Gui  Graphical interface  TK running is not stuck

Python Tkinter GUI is not stuck in running, multi -threading solution to the interface card death problem



Foreword

The TKINTER module (TK interface) is the interface of the Python standard TK GUI toolkit .TK and TKINTER can be used under most UNIX platforms, and can also be applied to Windows and Macintosh systems. The follow -up version of TK8.0 can achieve local windows style and run well in most platforms. Python can quickly create GUI applications using TKINTER. Since TKINTER is built -in Python installation package, as long as Python is installed, Python is installed. It can be imported tkinter library, and Idle is also written in Tkinter. For a simple graphical interface TKINTER, it can still be freely cope. ——In the Python GUI Programming (TKINTER) | Cainiao Tutorial


1. Problem description

When the Python GUI program is running, if you click the button to run a more time -consuming operation, the interface will be stuck to indicate that the response is not responding, causing other components to operate.

2. Solving ideas

The reference thread is used to execute the function of the button button binding events. The reality does not run stuck to solve the interface stuck.

3. Operation effect

Fourth, code example

1. Perform the thread method of the Button button to bind the event function

import threading
def thread_it(func, *args):
    """Packing the function into the thread"""
    self.myThread = threading.Thread(target=func, args=args)
    self.myThread .setDaemon(True)    # The main thread exits, just let the sub -thread follow the exit,Regardless of whether it is running. 
    self.myThread .start()

2. Full code

import sys
import time
import tkinter as tk
from tkinter.messagebox import askyesno
from tkinter.scrolledtext import ScrolledText
import threading


class TestGui(object):
    def __init__(self, init_window_name):
        self.init_window_name = init_window_name
        self.init_window_name.title("Packing the Button method into the thread, the real run is not stuck test")    # Set the window title
        self.init_window_name.geometry('700x350')    # Set the window size
        """Click to close the window pop -up window in the upper right corner"""
        self.init_window_name.protocol('WM_DELETE_WINDOW', lambda: self.thread_it(self.clos_window))
        """Create a component container"""
        self.log_frame = tk.Frame(self.init_window_name)    # Create a container for storage logo
        self.log_frame.grid(padx=20, pady=0, row=1, column=0, sticky=tk.W)
        self.runs_button_frame = tk.Frame(self.init_window_name)    # Create a container for storage logo
        self.runs_button_frame.grid(padx=20, pady=0, row=2, column=0, sticky=tk.W)
        """Log box"""
        self.run_log = ScrolledText(self.log_frame, font=('Kaiti ", 13), width=69, height=17)
        self.run_log.grid(padx=20, pady=5, row=0, column=0)
        """Operation button"""
        self.start_run1 = tk.Button(self.runs_button_frame, text='Start print 1', font=('Xing Kai', 15, 'bold'), fg="white", bg="#1E90FF", width=25, command=lambda: self.thread_it(self.print1))
        self.start_run1.grid(padx=20, pady=0, row=0, column=1)
        self.start_run2 = tk.Button(self.runs_button_frame, text='Start print 2', font=('Xing Kai', 15, 'bold'), fg="white", bg="#1E90FF", width=25, command=lambda: self.thread_it(self.print2))
        self.start_run2.grid(padx=35, pady=0, row=0, column=2)

    def thread_it(self, func, *args):
        """Packing the function into the thread"""
        self.myThread = threading.Thread(target=func, args=args)
        self.myThread .setDaemon(True)    # The main thread exits, just let the sub -thread follow the exit,Regardless of whether it is running. 
        self.myThread .start()

    def print1(self):
        for i in range(100):
            tip_content = f'No. 1} times print -I am Xiaozhou 1'
            self.run_log_print(message=tip_content)
            time.sleep(0.1)    # #  
        self.run_log_print(message='I am Xiaozhou 1 -Printing complete')

    def print2(self):
        for i in range(100, 200):
            tip_content = f'No. {i} times print -I am Xiaozhou 2'
            self.run_log_print(message=tip_content)
            time.sleep(0.05)    # #  
        self.run_log_print(message='I am Xiaozhou 2 -Printing complete')

    def run_log_print(self, message):
        self.run_log.config(state=tk.NORMAL)
        self.run_log.insert(tk.END, "\n" + message + "\n")
        self.run_log.see(tk.END)
        self.run_log.update()
        self.run_log.config(state=tk.DISABLED)

    def clos_window(self):
        ans = askyesno(title='Xiaozhou Assistant v1.1 warning', message='Are you sure the exit program? \ n is exiting, otherwise continue! ')
        if ans:
            self.init_window_name.destroy()
            sys.exit()
        else:
            return None


if __name__ == '__main__':
    """Packing the Button method into the thread, the reality is not stuck."""
    """Examine a parent window"""
    init_window = tk.Tk()
    """TK interface top"""
    init_window.attributes("-topmost", 1)
    """Create GUI class objects"""
    test_gui = TestGui(init_window)
    """Initialize GUI component"""
    init_window.mainloop()

5. Specific use of components

Note: The key parts in the code are written. This blog just introduces how to solve the problem of the tk interface running stuck;
For the specific use of components, please refer to another blog of my: update
Free online video to GIF URL:https://www.img2go.com/zh/convert-video-to-gif

Intelligent Recommendation

Python Draw a GUI interface with Tkinter

Python Draw a GUI interface with Tkinter Foreword Code interface Tkinter common control END Foreword Python, this name has been listening for a few years, has not been going to study, and recently, fi...

Ubuntu system interface card death solution record

Using Ubuntu 20.04 version, because there are a lot of content in the Ubuntu system. When the system interface is stuck, if the shutdown is mandatory, the damage is too large, and the system may not b...

Python uses tkinter to create a GUI interface (1)

Precautions: 1, the same window can not share the grid and pack 2, the button control function in the button control is a function with parameters, the group to use lambda, and if you use the loop to ...

Design of tkinter pythonic python gui interface design

Record ui design, control id is a relatively tedious thing. In addition, assignments and read data is relatively complicated, very pythonic. There is no God horse elegant way to do it? life is short. ...

More Recommendation

[Python] Tkinter Graphical Interface Design (GUI)

Introduction As a Python developer, graphical user interface (GUI) development is one of the necessary skills. Currently, the market supports There are many "GUI toolkits" for Python, each w...

Python|Tkinter implements a simple GUI interface

Welcome to click "The Beauty of Algorithms and Programming" ↑ Follow us! This article was first published on the WeChat public account: "The Beauty of Algorithms and Programming&qu...

Python programming: tkinter creates a GUI visual interface

Simply test tkinter Interface effect: Reference: Tkinter module common parameters (python3) Tkinter simple tutorial Tkinter instance learning of pyhon Python basic summary (7) (Tkinter GUI programming...

Python graphical interface GUI Tkinter example

Python implements a graphical interface...

Tkinter layout of Python graphical interface GUI programming

Reference documents: 1. Window 2. Layout Grid row: the control is placed on the specified row column: the control is placed in the specified column padx: the left and right spacing of the control from...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top