Python Forum

Full Version: tkinter and multiprocessing
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Just a simple tkinter window using multiprocessing and labels

import multiprocessing as mp
import random as rnd
import tkinter as tk

'''
    Function for updating labels
    Creates the que
    Add to the que
    Set label text for que
    Call root.after for continuous call
'''
def get_num(root, label):
    myque = mp.Queue()
    myque.put(rnd.randint(1, 100))
    label['text'] = f'Process {myque.get()} running...'
    root.after(1000, lambda: get_num(root, label))

'''
    Tkinter window
'''
root = tk.Tk()
root.title('Running Processes')
root.columnconfigure(0, weight=1)
root.geometry('+300+300')

'''
    Two list, one to hold labelframes and one to hold labels
'''
labels = []
labelframes = []

'''
    Set variable j to for labelframe numbers
'''
j = 1

'''
    Using for loop to add 10 labels
    using j to number labelframes
    create and append labelframes to the labelframes list
'''
for i in range(10):
    j = j if i % 2 == 0 else(j if i % 3 == 0 else j+1)
    labelframes.append(tk.LabelFrame(root, text=f'Processes for frame {j}'))
    labelframes[i].grid(column=0, row=i, sticky='new', pady=5, padx=5)

    '''
    parent is used to place labels in the labelframes. Using i % n in this example
    '''
    parent = labelframes[0] if i % 2 == 0 else(labelframes[1] if i % 3 == 0 else labelframes[i])

    '''
    Create and append labels to the labels list
    Using parent to color background of grouped labels in labelframe
    '''
    labels.append(tk.Label(parent, anchor='w', padx=5, width=50))
    labels[i]['bg'] = 'sandybrown' if parent == labelframes[0] \
    else('tan' if parent == labelframes[1] else 'ivory2')
    labels[i]['relief'] = 'ridge'
    labels[i].grid(column=0, row=i, sticky='new', pady=5, padx=5)

    '''
    Create and start the process
    '''
    process = mp.Process(target=get_num, args=(root, labels[i],))
    process.start()
    process.join()

    '''
    Use root.after to call the get_num function
    '''
    root.after(1, get_num, root, labels[i])
root.mainloop()