using multiprocessing module for updating tkinter gui

  • Last Update :
  • Techknowledgy :

You missed out an important part, you should protect your calls with a __main__ trap:

if __name__ == '__main__':
   q = Queue.Queue()
# Create a thread and run GUI & QueueHadnler in it
t1 = multiprocessing.Process(target = GenerateData, args = (q, ))
t2 = multiprocessing.Process(target = QueueHandler, args = (q, ))

   ....

Edit: just spotted another issue, you should be using Queue from the multiprocessing module, not from Queue:

from multiprocessing
import Queue
# Test Code
for Tkinter with threads
import Tkinter as Tk
import multiprocessing
from Queue
import Empty, Full
import time

class GuiApp(object):
   def __init__(self, q):
   self.root = Tk.Tk()
self.root.geometry('300x100')
self.text_wid = Tk.Text(self.root, height = 100, width = 100)
self.text_wid.pack(expand = 1, fill = Tk.BOTH)
self.root.after(100, self.CheckQueuePoll, q)

def CheckQueuePoll(self, c_queue):
   try:
   str = c_queue.get(0)
self.text_wid.insert('end', str)
except Empty:
   pass
finally:
self.root.after(100, self.CheckQueuePoll, c_queue)

# Data Generator which will generate Data
def GenerateData(q):
   for i in range(10):
   print "Generating Some Data, Iteration %s" % (i)
time.sleep(2)
q.put("Some Data from iteration %s \n" % (i))

if __name__ == '__main__':
   # Queue which will be used
for storing Data

q = multiprocessing.Queue()
q.cancel_join_thread() # or
else thread that puts data will not term
gui = GuiApp(q)
t1 = multiprocessing.Process(target = GenerateData, args = (q, ))
t1.start()
gui.root.mainloop()

t1.join()
t2.join()

Suggestion : 2

Aug 30, 2021

# my_app.py

import tkinter as tk

from mp_model
import MyModel

class MyApp:
   def __init__(self):
   self._root = tk.Tk()
self.status = tk.StringVar()
self.status.set('Status')
self.label = tk.Label(self._root, textvariable = self.status)
self.btn = tk.Button(self._root, text = 'Run', command = self.run_model)

self.label.pack()
self.btn.pack()

def run(self):
   self._root.mainloop()

def run_model(self):
   model = MyModel(status_var = self.status)
model.run()

if __name__ == '__main__':
   app = MyApp()
app.run()
# my_model.py

from multiprocessing
import Pool
import time
from timeit
import default_timer as timer
import multiprocessing as mp

import pandas as pd

def func_for_mp(name: str, ds_value: pd.Series) - > pd.Series:
   print(f 'Doing {name}.')

res_chunk = ds_value * 2.

time.sleep(2)

return res_chunk

class MyModel:
   def __init__(self, status_var = None):
   self.status_var = status_var

def run(self):
   self._outer_loop()

def _outer_loop(self):
   names = ['Name 1', 'Name 2']
for name in names:
   self.status_var.set(name)
self._loop_with_mp(name)

def _loop_with_mp(self, name: str):
   all_values = pd.Series(range(35))

n_cpu = mp.cpu_count()
chunk_size = int(len(all_values) / n_cpu) + 1
ds_chunks = [
   all_values.iloc[i: i + chunk_size]
   for i in range(0, len(all_values), chunk_size)
]

start = timer()

with Pool(processes = n_cpu) as pool:
   args = [(name, ds_chunk) for ds_chunk in ds_chunks]
results = pool.starmap(func_for_mp, args)

end = timer()
print(f 'Total elapsed time: {end - start}')
listen_addresses = '*'
port = 5432
max_connections = 100
# TYPE DATABASE USER ADDRESS METHOD

# "local"
is
for Unix domain socket connections only
local all all peer
local all all trust

# IPv4 local connections:
   host all all 192.168 .7 .1 / 24 trust
``
`ts
import {
  ConnectedSocket,
  MessageBody,
  OnGatewayConnection,
  OnGatewayDisconnect,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
} from '@nestjs/websockets';

import { Server } from 'socket.io';
`
``

Suggestion : 3

Summary: in this tutorial, you’ll learn how to use the Tkinter after() method to schedule an action after a timeout has elapsed.,Use the Tkinter after() method to schedule an action that will run after a timeout has elapsed,The __init__() method uses the after() method to schedule an action that updates the current time to the label every second:,Home » Tkinter » How to Schedule an Action with Tkinter after() method

All Tkinter widgets have the after() method with the following syntax:

.wp - block - code {
      border: 0;
      padding: 0;
   }

   .wp - block - code > div {
      overflow: auto;
   }

   .shcb - language {
      border: 0;
      clip: rect(1 px, 1 px, 1 px, 1 px); -
      webkit - clip - path: inset(50 % );
      clip - path: inset(50 % );
      height: 1 px;
      margin: -1 px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1 px;
      word - wrap: normal;
      word - break: normal;
   }

   .hljs {
      box - sizing: border - box;
   }

   .hljs.shcb - code - table {
      display: table;
      width: 100 % ;
   }

   .hljs.shcb - code - table > .shcb - loc {
      color: inherit;
      display: table - row;
      width: 100 % ;
   }

   .hljs.shcb - code - table.shcb - loc > span {
      display: table - cell;
   }

   .wp - block - code code.hljs: not(.shcb - wrap - lines) {
      white - space: pre;
   }

   .wp - block - code code.hljs.shcb - wrap - lines {
      white - space: pre - wrap;
   }

   .hljs.shcb - line - numbers {
      border - spacing: 0;
      counter - reset: line;
   }

   .hljs.shcb - line - numbers > .shcb - loc {
      counter - increment: line;
   }

   .hljs.shcb - line - numbers.shcb - loc > span {
      padding - left: 0.75 em;
   }

   .hljs.shcb - line - numbers.shcb - loc::before {
      border - right: 1 px solid #ddd;
      content: counter(line);
      display: table - cell;
      padding: 0 0.75 em;
      text - align: right; -
      webkit - user - select: none; -
      moz - user - select: none; -
      ms - user - select: none;
      user - select: none;
      white - space: nowrap;
      width: 1 % ;
   }
widget.after(delay, callback = None) Code language: Python(python)

Let’s see the following program:

import tkinter as tk
from tkinter
import ttk
import time

class App(tk.Tk):
   def __init__(self):
   super().__init__()

self.title('Tkinter after() Demo')
self.geometry('300x100')

self.style = ttk.Style(self)

self.button = ttk.Button(self, text = 'Wait 3 seconds')
self.button['command'] = self.start
self.button.pack(expand = True, ipadx = 10, ipady = 5)

def start(self):
   self.change_button_color('red')
time.sleep(3)
self.change_button_color('black')

def change_button_color(self, color):
   self.style.configure('TButton', foreground = color)

if __name__ == "__main__":
   app = App()
app.mainloop() Code language: Python(python)

To fix the issue, you can use the after() method to schedule the action that updates the color of the button instead of suspending the main thread execution. For example:

import tkinter as tk
from tkinter
import ttk
import time

class App(tk.Tk):
   def __init__(self):
   super().__init__()

self.title('Tkinter after() Demo')
self.geometry('300x100')

self.style = ttk.Style(self)

self.button = ttk.Button(self, text = 'Wait 3 seconds')
self.button['command'] = self.start
self.button.pack(expand = True, ipadx = 10, ipady = 5)

def start(self):
   self.change_button_color('red')
self.after(3000, lambda: self.change_button_color('black'))

def change_button_color(self, color):
   self.style.configure('TButton', foreground = color)
print(color)

if __name__ == "__main__":
   app = App()
app.mainloop() Code language: Python(python)

The following method returns the current time in the string format:

def time_string(self):
   return time.strftime('%H:%M:%S') Code language: Python(python)

The __init__() method uses the after() method to schedule an action that updates the current time to the label every second:

self.label.after(1000, self.update) Code language: Python(python)

Suggestion : 4

Tkinter is a GUI toolkit used in python to make user-friendly GUIs.Tkinter is the most commonly used and the most basic GUI framework available in python. Tkinter uses an object-oriented approach to make GUIs.Note: For more information, refer to Python GUI – tkinter ,Last Updated : 24 Jan, 2022,Difficulty Level : Easy,Text Widget is used where a user wants to insert multiline text fields. This widget can be used for a variety of applications where the multiline text is required such as messaging, sending information or displaying information and many other tasks. We can insert media files such as images and links also in the Textwidget.Syntax:  

Text Widget is used where a user wants to insert multiline text fields. This widget can be used for a variety of applications where the multiline text is required such as messaging, sending information or displaying information and many other tasks. We can insert media files such as images and links also in the Textwidget.
Syntax: 
 

T = Text(root, bg, fg, bd, height, width, font, ..)