1

I want to make a small program which plays a song and an image pops up while the mouse cursor is moved. I have 3 functions for 3 actions and I want to run them at the same time but I can't accomplish it. Could you help me?

import random
import threading
import pyautogui
import pygame

from tkinter import *


def play_song():
    file = 'Troll_Song.ogg'

    pygame.mixer.init()
    pygame.mixer.music.load(file)
    pygame.mixer.music.play()

    while pygame.mixer.music.get_busy():
        pygame.time.Clock().tick(10)


def create_window():
    while True:
        root = Tk()
        root.title('Trololo...')

        photo = PhotoImage(file='trollface.gif')
        label = Label(root, image=photo)
        label.pack()

        w = 620 # width for the Tk root
        h = 620 # height for the Tk root

        # get screen width and height
        ws = root.winfo_screenwidth() # width of the screen
        hs = root.winfo_screenheight() # height of the screen

        # random positions of the window
        x = random.randint(0, ws - 620)
        y = random.randint(0, hs - 620)

        # set the dimensions of the screen
        # and where it is placed
        root.geometry('%dx%d+%d+%d' % (w, h, x, y))

        root.mainloop()


def mouse_move():
    width, height = pyautogui.size()

    while True:
        x = random.randint(0, width)
        y = random.randint(0, height)

        pyautogui.moveTo(x, y, duration=0.3)


if __name__ == '__main__':
    t1 = threading.Thread(target=create_window())
    t2 = threading.Thread(target=play_song())
    t3 = threading.Thread(target=mouse_move())

    t1.start()
    t2.start()
    t3.start()
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
sziko
  • 53
  • 2
  • 11

1 Answers1

2

I don't know if it's the only problem with your code, but I can tell about threading -- target has to be a function, instead you call functions, making them run in main thread. So if first function is an infinite loop -- program will not create any threads, because it will stuck executing the first function. Here is how you do it:

t1 = threading.Thread(target=create_window)
t2 = threading.Thread(target=play_song)
t3 = threading.Thread(target=mouse_move)
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79