This question already has answers here:
closing tkmessagebox after some time in python
(4 answers)
Closed last month.
Im trying to make an idle program which shuts down my computer after a length of time. At the moment, I am testing tkinter yes or no prompt to make sure if the user is still awake. I want it to be if the user hasn't answered in 30 seconds, then it moves the mouse over to No and clicks on it. But it seems I can't put both tkinter prompt and pyautogui together.
import tkinter as tk
from tkinter import messagebox
import time
import pyautogui
while True:
result = messagebox.askyesno(
title='Yes No Demo',
message='Are you awake?',
detail='Click No to stay active'
)
pyautogui.moveTo(1026, 620, duration = 0)
time.sleep(3)
pyautogui.click()
if result == "True":
time.sleep(3)
else:
break
Well, your question title and code don't make sense together. If you wonder how you can shut your PC down, import sys lib and learn about the CMD shutdown commands.
I have written a python script that draws a GUI containing Graphs plotting various metrics such as CPU temperature, Ram usage etc. for my Rasberry pi v4 . The source code of the script is outlined below:
`
#!/usr/bin/env python3
#Import required modules
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import time
from gpiozero import CPUTemperature
import os
import psutil
import sys
#Create application GUI
Main_Window=tk.Tk()
Main_Window.title("Monitors v1.0")
window_width = 800
window_height = 400
Main_Window.resizable(False,False)
Main_Window.geometry(f'{window_width}x{window_height}')
#Set up the layout of the graphs .There will be 4 graphs plotting:
#CPU Temperature in Celsius,RAM,CPU and Disk usage usage in %
fig,(axs)=plt.subplots(2,2,constrained_layout=True,figsize=(8, 4))
canvas=FigureCanvasTkAgg(fig, Main_Window)
canvas.get_tk_widget().place(x=0,y=0)
fig.suptitle('Performance Metrics')
axs[0,0].set_ylabel('CPU Temperature(C)')
axs[0,0].set_xlabel('Time(Sec)')
axs[0,1].set_ylabel('RAM Usage(%)')
axs[0,1].set_xlabel('Time(Sec)')
axs[1,0].set_ylabel('CPU Usage(%)')
axs[1,0].set_xlabel('Time(%)')
axs[1,1].set_ylabel('Disk Usage(%)')
axs[1,1].set_xlabel('Time(%)')
#Initialize data buffers and plots
temp=[]
RAM=[]
CPU=[]
Disk=[]
axs[0,0].plot(temp)
axs[0,1].plot(RAM)
axs[1,0].plot(CPU)
axs[1,1].plot(Disk)
#Run the script for 50 samples
for _ in range(50):
#Sampling the metrics.
temp.append(CPUTemperature().temperature)
RAM.append(psutil.virtual_memory()[2])
load1, load5, load15 = psutil.getloadavg()
cpu_usage = (load15/os.cpu_count()) * 100
CPU.append(cpu_usage)
Disk.append(psutil.disk_usage('/').percent)
#Update the Plots every 200 msec
time.sleep(0.2)
canvas.draw()
axs[0,0].clear()
axs[0,1].clear()
axs[1,0].clear()
axs[1,1].clear()
axs[0,0].set_ylabel('CPU Temperature(C)')
axs[0,0].set_xlabel('Time(Sec)')
axs[0,1].set_ylabel('RAM Usage(%)')
axs[0,1].set_xlabel('Time(Sec)')
axs[1,0].set_ylabel('CPU Usage(%)')
axs[1,0].set_xlabel('Time(%)')
axs[1,1].set_ylabel('Disk Usage(%)')
axs[1,1].set_xlabel('Time(sec)')
axs[0,0].plot(temp)
axs[0,1].plot(RAM)
axs[1,0].plot(CPU)
axs[1,1].plot(Disk)
Main_Window.mainloop()
sys.exit()
I have also created a bash command so that I can run the script with a simple command via the terminal. The script runs as supposed to be plotting 50 measurements of the metrics described before in real time but there are two issues I am facing. First, despite clicking the close button(the classic X button on the top right corner) the window wont close until the 50 measurements are done. Then if I close the window after the measurements are done, then the terminal looks busy as if the script is still running. Any ideas why these things happen?
I tried adding a sys.exit() command after mainloop() to make sure the script exits after the main window is closed but it did not help.
When you enter your for-loop, your program runs all 50 iteration of that code block until it exits and runs code below. This is toxic for different reasons. Overall, your mainloop is interrupted, events such as mouse or key input won't be processed. This includes clicking X, the window simply does not proceed this message.
However, Tkinter provides tools for such operations. You could use after for it:
Example:
def my_function():
#useful instructions
for i in range(50):
ms = 20*i
root.after(ms, my_function)
After returns immediately and won't block your application, means still responsive to input. But since you still want to sleep in the block of code, you could use something like tksleep.
I know I can use time.sleep(), but I need something that would affect whole script.It is automatic test homework and aplication buttons are clicked almost instantly. It is a bit anoying because I cant see if everything is working as supposed(still learning).
import pyautogui
import time
from pywinauto.application import Application
app = Application(backend="uia").start(r"C:\Users\User\Desktop\WPF_RentACar_3maj\WPFRentACar\bin\Debug\WPFRentACar.exe")
pyautogui.FAILSAFE = True
#app.LoginWIndow.print_control_identifiers()
dlg =app.LoginWindow
dlg.MaximizeButton.click()
dlg.MinimizeButton.click()
dlg.MaximizeButton.click()
dlg.Restore.click()
try:
dlg.Edit1.type_keys("123")
dlg.Edit2.type_keys("123")
dlg.LoginButton.click()
dlg.Button1.click()
finally:
print("Cant login with wrong credentials!")
time.sleep(2)
dlg.Edit1.type_keys("'^a{BACKSPACE}")
dlg.Edit2.type_keys("'^a{BACKSPACE}")
dlg.LoginButton1.click()
time.sleep(5)
time.sleep() does stop the whole script. Or are you using threading or python 2? Also can you tell us what you are also trying to automate.
I tried to use this script to prevent windows screen lock. The script works for moving the mouse, but it doesn't prevent windows 10 from locking.
import pyautogui
import time
import win32gui, win32con
import os
Minimize = win32gui.GetForegroundWindow()
win32gui.ShowWindow(Minimize, win32con.SW_MINIMIZE)
x = 1
while x == 1:
pyautogui.moveRel(1)
pyautogui.moveRel(-1)
time.sleep (300)
Yes it can. But sadly not by moving mouse which I don't know why and would like to know. So, my suggestion is to use pyautogui KEYBOARD EVENTS if possible. I have solved my problems by using VOLUME-UP & VOLUME-DOWN keys. Example code is provided below:
import pyautogui
import time
while True:
pyautogui.press('volumedown')
time.sleep(1)
pyautogui.press('volumeup')
time.sleep(5)
You can use any other keys if you want.
import ctypes
# prevent
ctypes.windll.kernel32.SetThreadExecutionState(0x80000002)
# set back to normal
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)
https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setthreadexecutionstate
Tested on python 3.9.1, win 10 64bit
I have a program which makes the mouse go crazy and point randomly on different places on screen.
it works just fine, but when i go to task manager or simply click ctrl + alt + delete, it stops functioning, even when im exiting task manager.
any help?
(the program still seems to run in the proccess list, but simply doesn't do anything)
the program:
from win32api import SetCursorPos,GetSystemMetrics
from time import sleep
from random import uniform
from win32console import GetConsoleWindow
from win32gui import ShowWindow
win = GetConsoleWindow()
ShowWindow(win,0)
def click(x,y):
SetCursorPos((x,y))
while True:
click((int)(uniform(GetSystemMetrics(0),10)),(int)(uniform(GetSystemMetrics(1),10)))
sleep(0.02)