0

I amended code from a previous post from stackoverflow. It is suppose to display the window and trigger a sound after some calculation is completed.

import tkinter as tk
import winsound
import threading

class Calculate_Window:
    def __init__(self, val_1, val_2):
        self.root = tk.Tk()
        self.root.title("Calculate")
        
        def calculate(val_1, val_2):
            add_vals = float(val_1) + float(val_2)
            return str(add_vals)
        
        str_add = calculate(val_1, val_2)
        
        self.lbl = tk.Label(self.root, text=str_add)
        self.lbl.pack()

        threading.Thread(target=lambda:winsound.PlaySound("SystemExit", winsound.SND_ALIAS)).start()
        
        self.root.mainloop()
 
    def __play_sound(self):
        winsound.PlaySound("SystemExit", winsound.SND_ALIAS)
        
Calculate_Window(1,2)

But I do not understand why threading shifts the triggering of winsound to after the calculation function is complete and the tkinter GUI pop ups. Normally when you run threading, shouldn't the threads run concurrently? Like in the code below, the two threads run concurrently.

import threading
import time

class myThread(threading.Thread):
    def __init__(self, threadId, name, count):
        threading.Thread.__init__(self)
        self.threadId = threadId
        self.name = name
        self.count = count

    def run(self):
        print("Starting: " + self.name + "\n")
        print_time(self.name, 1,self.count)
        print("Exiting: " + self.name + "\n")



def print_time(name, delay, count):
    while count:
        time.sleep(delay)
        print ("%s: %s %s" % (name, time.ctime(time.time()), count) + "\n")
        count -= 1

thread1 = myThread(1, "Thread1", 10)
thread2 = myThread(2, "Thread2", 5)


thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("Done main thread")

Please advise and thanks.

Kent Choo
  • 35
  • 5
  • 2
    You started the thread after you executed `calculate()` and before `mainloop()`, so the sound would be played around the same time the window was displayed. Note that it is not guaranteed that `threading.Thread(...).start()` will start the thread immediately. Actually you don't need to play the sound using threading module, just call `winsound.PlaySound(...)` with the flag `SND_ASYNC`. – acw1668 Jul 28 '22 at 09:13
  • @acw1668 Noted with thanks. – Kent Choo Jul 28 '22 at 09:44

0 Answers0