[英]How to start threads at the same time in Python
我想制作一個小程序,播放一首歌,並在移動鼠標光標時彈出一個圖像。 我有3個功能,可以執行3個動作,但我想同時運行它們,但我無法完成。 你可以幫幫我嗎?
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()
我不知道這是否是代碼的唯一問題,但我可以講講線程化- target
必須是一個函數,而您必須調用函數,使它們在主線程中運行。 因此,如果第一個函數是一個無限循環-程序將不會創建任何線程,因為它將卡死執行第一個函數。 這是您的操作方式:
t1 = threading.Thread(target=create_window)
t2 = threading.Thread(target=play_song)
t3 = threading.Thread(target=mouse_move)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.