Home > Net >  how to run code pyautogui after plt.show()
how to run code pyautogui after plt.show()

Time:03-16

I want move a chart after run plt.show() but my code pyautogui dont run unless I close the chart. I searched on Google but inefficient.

plt.show()
pyautogui.hotkey('winleft', 'left')
pyautogui.hotkey('winleft', 'up')
pyautogui.press('esc')

CodePudding user response:

What you want is a way to have plt.show() be "non-blocking", that is, have the function call return immediately instead of waiting for the user to close the window. To do this, pass block=False. So your code should be:

plt.show(block=False)
pyautogui.hotkey('winleft', 'left')
pyautogui.hotkey('winleft', 'up')
pyautogui.press('esc')

CodePudding user response:

Threading might be a suitable method. Here's an example:

import numpy as np
from matplotlib import pyplot as plt
import pyautogui
import time
from threading import Thread


def pressKeys():
    time.sleep(1)
    pyautogui.hotkey('winleft', 'left')
    pyautogui.hotkey('winleft', 'up')
    pyautogui.press('esc')


t1 = Thread(target=pressKeys)
t1.start()
plt.plot([1,2,3],[1,8,27])
plt.show()

With threading, there's the main thread, which is what your program normally runs in, and then you can create additional ones. In concocting this example, I found that, unfortunately, matplotlib encounters errors when not run in the main thread. If your objective is to make the plot full screen, then there are better ways to do it than pyautogui (there's probably some function in the windows api). Short of that, you could at least make sure that the window is open before pressing the keys (Hence the call to time.sleep.) Better yet (but more time consuming -- not the module/import), use matplotlib to set the title and use psutil to periodically check if a a process exists with that title, then when one does, break from a loop and trigger the key presses.

  • Related