【问题标题】:How to start threads at the same time in Python如何在 Python 中同时启动线程
【发布时间】:2017-08-26 16:37:52
【问题描述】:

我想制作一个小程序播放一首歌曲并在移动鼠标光标时弹出一个图像。我有 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()

【问题讨论】:

    标签: python multithreading tkinter pygame python-multithreading


    【解决方案1】:

    我不知道这是否是你的代码的唯一问题,但我可以告诉你线程——target 必须是一个函数,而不是你调用函数,使它们在主线程中运行。所以如果第一个函数是一个无限循环——程序将不会创建任何线程,因为它会卡住执行第一个函数。以下是你的做法:

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

    【讨论】:

      猜你喜欢
      • 2017-08-27
      • 2021-01-22
      • 2019-01-03
      • 1970-01-01
      • 2021-11-21
      • 2011-03-23
      • 2023-03-06
      • 2017-05-05
      • 2015-06-23
      相关资源
      最近更新 更多