SoFunction
Updated on 2024-11-18

python using PySimpleGUI to set up a progress bar and control use

PySimpleGUI feels easier to use than tkinter, but of course I haven't used either much. Just learning to simulate the task progress completion.

mounting

pip install PySimpleGUI

I. Simple progress bar use

PySimpleGUI has a control that displays a progress bar with a single command.one_line_progress_meter

import time
import PySimpleGUI as sg


if __name__ == '__main__':
    sg.one_line_progress_meter('Progress bar title',
                               10,
                               100,
                               'key1',
                               'Content')
    # sg.one_line_progress_meter()
    (10)

进度条1

Basic parameters
The preceding parameters represent
Progress Bar Title, The
The current progress of the progress bar, the
Maximum progress of the progress bar.
the key of the progress bar, (the same key means the same progress bar)
Progress bar passes in parameters (can be multiple non-keyword parameters).

sg.one_line_progress_meter('Progress bar title',
                           10,
                           100,
                           'key1',
                           'Content 1')

Other common parameters orientation
Due to the existence of the *args parameter, if you want to pass a custom parameter, you need to pass the basic parameter in a non-keyword form. Of course, you can also not pass custom parameters.
orientation Indicates whether the progress bar is horizontal or vertical.
h horizontal v vertical (default)

 sg.one_line_progress_meter(title='Progress bar title 2',
                               current_value=20,
                               max_value=100,
                               key='key2',
                               orientation='h')

进度条2

Simulate the progress bar filling up step by step

import time
import PySimpleGUI as sg


if __name__ == '__main__':
    for i in range(1000):
        (0.02)    # Simulation 0.02s done in a thousand #
        sg.one_line_progress_meter(
            'Progress bar',
            i+1,
            1000,
            'key',
            'Testing the use of progress bars',
            orientation='h'
        )

进度条3

This hibernation time can be used as time to complete a task. Without completing a bit of the task the progress bar will increase.

But in reality there are many time-consuming tasks that block the progress bar when it actually runs. So the progress bar will fall into an unresponsive state (like the first image). Therefore, we usually use multi-threaded execution for time-consuming tasks, and find a way to notify the progress bar to update its status after the execution is completed. Note (the PySimpleGUI component needs to run in the main thread, see the source documentation for instructions).

The one_line_progress_meter is convenient, but the style is uncontrollable and there are a lot of uncaring displays on it that can't be removed.

Attached. popup use of PySimpleGUI.

('Attention!')
sg.popup_ok('Default popup')
sg.popup_yes_no('Popups with Yes and No buttons')
sg.popup_cancel('Popup with cancel button')
sg.popup_ok_cancel('Popup with OK and cancel buttons')
sg.popup_error('Popup with red error button')
sg.popup_auto_close('Pop-ups that close automatically after a few seconds')
sg.popup_auto_close('Pop-up window that closes automatically after 10 seconds', auto_close_duration=10)

Second, the use of progress bar controls

Common method to display progress bar control. Need to know roughly the relationship between the layout and the window.

import PySimpleGUI as sg

# Layout, a user-defined two-dimensional list.
# Elements in the first dimension are in different rows, elements in the second dimension are in the same row and in different columns.
# The list defined here consists of three parts: Text file ProgressBar Cancel Cancel button.
# Text Progress etc. have their own parameter settings such as size etc. We won't go into that here.
layout = [[('Progress in the completion of the mission')],
          [(1000, orientation='h', size=(20, 20), key='progressbar')],
          [()]]

# window just loads the customized layout out The first parameter is the window title.
window = ('Robot execution progress', layout)

# Get the progress bar based on the key value
progress_bar = window['progressbar']

# window's read function is divided into synchronous and asynchronous.
# Without the timeout parameter is a synchronized function that waits until the button is manually clicked before returning.
# Asynchronous functions with a timeout parameter other than None will produce results if there is no time in the timeout period or if a button is clicked.
# The asynchronous approach does not block the operation of later programs.
for i in range(1000):	# Cycle
    event, values = (timeout=10)
    if event == 'Cancel' or event is None:
        break
    progress_bar.UpdateBar(i + 1)

()

进度条4

Here the for loop is still used to fill the progress bar. The following uses threads to simulate the task progress to completion.

III. Simulation of mandate completion Progress bars

Use threads to simulate task progress to completion. Of course, there is no realistic task, so it is still composed using a for loop plus hibernation. Of course, there is still a difference with the original. Because the task is completed within the thread, after completion, you need to notify the main thread progress bar update.

import random
import time
from queue import Empty

import PySimpleGUI as sg
import threading
import queue

# Layout, a user-defined two-dimensional list.
# Elements in the first dimension are in different rows, elements in the second dimension are in the same row and in different columns.
# The list defined here consists of three parts: Text file ProgressBar Cancel Cancel button.
layout = [[('Progress in the completion of the mission')],
          [(100, orientation='h', size=(50, 20), key='progressbar')],
          [()]]

# window just loads the customized layout out The first parameter is the window title.
window = ('Robot execution progress', layout)

# Get the progress bar based on the key value
progress_bar = window['progressbar']

# Queue LIFO
q = ()


def task_1():
    global q
    for i in range(100):
        # because it is greater than the set timeout of 100ms to ensure that there is at most one element in the queue when it is read.
        (() + 0.1)
        (i+1)    # Put the current task completion into the queue

# Create multiple threads Set to start in protected mode, i.e., when the main thread finishes running, the child threads also stop running
worker_task = (target=task_1)
worker_task.setDaemon(True)
worker_task.start()

while True:     # Dead loop keeps reading from the queue until it reaches 100.
    # event is the event returned
    # e.g. after clicking Cancel event=Cancel
    event, values = (timeout=100)
    if event == 'Cancel' or event is None:
        # Click the cancel button or return event to None
        break

    # 10ms no action counts as a timeout event will equal __TIMEOUT__.
    # Don't really have to judge
    try:
        # get is waiting to read until the data is read
        # get_nowait does not wait and throws an exception if no data is read.
        progress_value = q.get_nowait()
    except Empty:   # If no data is read, continue
        continue
    else:   # Read the data
        progress_bar.UpdateBar(progress_value)
        if progress_value == 100:   # Progress full jump out of loop
            break

()

任务完成进度

Above is the details of python using PySimpleGUI to set the progress bar, more information about python PySimpleGUI progress bar please pay attention to my other related articles!