Python Forum
tkinter and multiprocessing
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
tkinter and multiprocessing
#1
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()
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020