1

マウスカーソルの移動中に曲を再生する小さなプログラムを作成し、画像をポップアップしたい。私は3つのアクションの3つの機能を持っていると同時にそれらを実行するが、私はそれを達成することはできません。私たちを手伝ってくれますか?Pythonで同時にスレッドを開始するには

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() 

答えて

2

それはあなたのコードの唯一の問題だ場合、私は知りませんが、私はスレッドについて伝えることができます - targetは、彼らがメインスレッドで実行すること、代わりにあなたが関数を呼び出し、機能にする必要があります。最初の関数が無限ループの場合、プログラムはスレッドを作成しません。なぜなら、最初の関数の実行がスタックされるからです。あなたのやり方は次のとおりです。

t1 = threading.Thread(target=create_window) 
t2 = threading.Thread(target=play_song) 
t3 = threading.Thread(target=mouse_move) 
+0

ありがとうございました。 – sziko

+0

@szikoようこそ –

関連する問題