Threading и MSS проблема - ошибка при запуске функции во второй раз - PullRequest
0 голосов
/ 07 апреля 2020

Я не могу понять, как заставить это работать. Я надеюсь, что вы мне поможете.

Я отредактировал код, чтобы сделать его более простым и коротким - вот почему он только что-то печатает, но этого достаточно, чтобы показать проблему.

Все есть работает нормально, пока я нажимаю кнопку ввода, чтобы остановить функции, и нажимаю кнопку (в окне Tkinter), чтобы снова запустить main_function().

Когда я выхожу из программы и снова запускаю функцию - все хорошо. Проблема возникает только тогда, когда я останавливаю функцию и запускаю ее во второй раз.

Надеюсь, я четко описал проблему, и комментарии в коде полезны.

Полученная ошибка:

Exception in thread Thread-5:
Traceback (most recent call last):
  File "path\threading.py", line 932, in _bootstrap_inner
   self.run()
  File "path\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "path/program.py", line 323, in fun_1
    temp_img = sct.grab(region)
  File "path\mss\windows.py", line 291, in grab
    raise ScreenShotError("gdi32.GetDIBits() failed.")

mss.exception.ScreenShotError: gdi32.GetDIBits() failed.

Код:

import threading
import keyboard
import time
import mss
import mss.tools

bot_stop = False


def main_function():   # I run this function by pressing button in tkinter window
    global bot_stop
    bot_stop = False

    # threading
    thread_1 = threading.Thread(target=fun_1)

    # start the thread if checkbox in tkinter window is ticked
    if checkbox_1.get():
        thread_1.start()

    # press enter to stop the main_function and fun_1, 'bot_stop_switch' is a callback
    keyboard.on_press_key('enter', bot_stop_switch)

    # run this loop as long as user will press "enter"
    while not bot_stop:
        print("main_function_is_running")
        time.sleep(1)


def fun_1():

    # make a screenshoot of selected region (this case: upper left main monitor corner)
    with mss.mss() as sct:
        region = {'top': 0, 'left': 0, 'width': 100, 'height': 100}
        temp_img = sct.grab(region)
        raw_bytes_1 = mss.tools.to_png(temp_img.rgb, temp_img.size)

    # check if something changed on the screen in the selected region as long as user will press "enter"
    while not bot_stop:
        temp_img = sct.grab(region)
        raw_bytes_2 = mss.tools.to_png(temp_img.rgb, temp_img.size)
        if raw_bytes_1 != raw_bytes_2:
            print("something changed in the screen corner!")
        time.sleep(0.5)


def bot_stop_switch(keyboard_event_info):
    global bot_stop

    bot_stop = True

    keyboard.unhook_all()
    print(keyboard_event_info)

1 Ответ

0 голосов
/ 08 апреля 2020

После нескольких часов тестирования я нашел решение, но понятия не имею, почему это имеет значение. Смысл в том, чтобы сделать первый снимок экрана temp_img = sct.grab(region) внутри основной функции (откуда мы начинаем поток для второй функции).

import threading
import keyboard
import time
import mss
import mss.tools

bot_stop = False
raw_bytes_1 = None
region = {}


def main_function():   # I run this function by pressing button in tkinter window
    global bot_stop
    global raw_bytes_1
    global region

    bot_stop = False

    # make a screenshoot of selected region (this case: upper left main monitor corner)
    with mss.mss() as sct:
        region = {'top': 0, 'left': 0, 'width': 100, 'height': 100}
        temp_img = sct.grab(region)
        raw_bytes_1 = mss.tools.to_png(temp_img.rgb, temp_img.size)

    # threading
    thread_1 = threading.Thread(target=fun_1)

    # start the thread is checkbox in tkinter window is ticked
    if checkbox_1.get():
        thread_1.start()

    # press enter to stop the main_function and fun_1
    keyboard.on_press_key('enter', bot_stop_switch)

    # run this loop as long as user will press "enter"
    while not bot_stop:
        print("main_function_is_running")
        time.sleep(1)


def fun_1():
    # check if something changed on the screen in the selected region as long as user will press "enter"
    while not bot_stop:
        temp_img = sct.grab(region)
        raw_bytes_2 = mss.tools.to_png(temp_img.rgb, temp_img.size)
        if raw_bytes_1 != raw_bytes_2:
            print("something changed in the screen corner!")
        time.sleep(0.5)


main_function()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...