Python loop only works when ran on visual studio code - while-loop

Im very new to python and I've been trying to make a simple macro that clicks a button whenever it sees it. It works perfectly when I run it manually on Visual studio code but closes immediately when I execute the file with python3.10.
import pyautogui
import time
time.sleep(5)
waitingloop = 1
while waitingloop == 1:
if pyautogui.locateCenterOnScreen("notif.png") == None:
time.sleep(0.5)
else:
pyautogui.click("notif.png")
time.sleep(0.5)
pyautogui.click(x=1751, y=792)
time.sleep(1)
pyautogui.click(x=1909, y=875, clicks=5, interval= 2)
time.sleep(0.5)
pyautogui.click(x=1751, y=792)
time.sleep(5)
pyautogui.click(x=956, y=344)
time.sleep(1)
pyautogui.keyDown("alt")
time.sleep(0.25)
pyautogui.press("tab")
time.sleep(0.25)
pyautogui.keyUp("alt")
pyautogui.click("chat.png")
break
How do I make a loop that only starts running after the expected input?

Related

How to generate accept signal for dialog.exec in PyQt5

In main.py
returnCode = self.rouDialogForm.exec_()
if returnCode == QtWidgets.QDialog.Accepted:
print(float(self.rouDialogForm.ui.leStartMhz.text()))
if returnCode ==QtWidgets.QDialog.Rejected:
print(float(self.rouDialogForm.ui.leStopMhz.text()))
In rouDialog.py
def setupUi(self, Dialog):
#GUI CODE
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
self.butConnect.clicked.connect(self.acceptDialog)
def acceptDialog(self):
self.accept()
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
#Label set texts are here
import myResources_rc
I can catch the Rejected signal that is generated after clicking the window closing icon and print out the required text from the line edit.
But when I press the button that will generate accept signal(but connect) program just crashes run time.
I tried different syntax and different imports to make it work.
attempt #1: in rouDialog.py instead of self.accept()
self.done(QtWidgets.QDialog.Accepted)
another attempt: in rouDialog.py instead of self.accept()
super(Ui_Dialog,self).accept()
another one:
QtWidgets.QDialog.accept(self)
SOLVED:
Adding this to my rouDialog.py solved all my problems.Hope it will help someone else in future.
self.butReadout.clicked.connect(Dialog.accept)
#QtCore.pyqtSlot()
def accept(self):
pass
Edit: I can't mark my answer as correct , since i need to wait 2 days.

Issue with using Leap motion and python

I am trying to write a basic program using leap motion, I just want to constantly run the on_frame method but the method only runs once and disconnecting the device does not call the on_disconnect method. The program will not run until I hit enter, What am I doing wrong? Thanks for the help :
import Leap, sys, thread
from Leap import CircleGesture, KeyTapGesture, ScreenTapGesture,SwipeGesture
class LeapMotionListener(Leap.Listener):
state_names = ["STATE_INVAILD","STATE_START","STATE_UPDATE", "STATE_END"]
def on_init(self, controller):
print "Initialized"
def on_connect(self, controller):
print "Connected"
controller.enable_gesture(Leap.Gesture.TYPE_CIRCLE);
controller.enable_gesture(Leap.Gesture.TYPE_KEY_TAP);
controller.enable_gesture(Leap.Gesture.TYPE_SCREEN_TAP);
controller.enable_gesture(Leap.Gesture.TYPE_SWIPE);
print "All gestures enabled"
def on_disconnect(self, controller):
print "Disconnected"
def on_exit(self, controller):
print "Exit"
def on_frame(self, controller):
frame= controller.frame()
print "\n Frame ID"+ str(frame.id)
print "num of hands: " +str(len(frame.hands))
print "num of gestures: " +str(len(frame.gestures()))
for gesture in frame.gestures():
if gesture.type is Leap.Gesture.TYPE_CIRCLE:
circle = Leap.CircleGesture(gesture)
elif gesture.type is Leap.Gesture.TYPE_SWIPE:
swipe = Leap.SwipeGesture(gesture)
elif gesture.type is Leap.Gesture.TYPE_KEY_TAP:
key_tap = Leap.KeyTapGesture(gesture)
elif gesture.type is Leap.Gesture.TYPE_SCREEN_TAP:
screen_tap = Leap.ScreenTapGesture(gesture)
def main():
listener= LeapMotionListener()
controller = Leap.Controller()
controller.add_listener(listener)
print "Press enter to quit: "
try:
sys.stdin.readline()
except KeyboardInterrupt:
pass
finally:
controller.remove_listener(listener)
if __name__ == "__main__":
main()
Your code runs fine from the command line. I.e:
> python scriptname.py
Are you running from Idle? if so, this part:
try:
sys.stdin.readline()
except KeyboardInterrupt:
pass
doesn't work. (See Python 3.2 Idle vs terminal) A similar issue might exist in other IDEs.
The following should work in Idle, but you have to use Ctrl-C to exit.
# Keep this process running until a Ctrl-C is pressed
print "Press Ctrl-C to quit..."
try:
while True:
time.sleep(1)
except:
print "Quiting"
finally:
# Remove the sample listener when done
controller.remove_listener(listener)
Quitting on any key stroke in both Idle and the command line seemed surprisingly difficult and complex when I tried it some time ago -- but then, I'm a Python duffer.

Confusion in JTextField () of jython in sikuli

This is my code :-
from javax.swing import *
class Example(JFrame):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
panel = JPanel()
panel.setLayout(None)
self.getContentPane().add(panel)
panel.setLayout(None)
area = JTextField('',15)
panel.add(JLabel("username:", SwingConstants.RIGHT))
panel.add(area)
self.setTitle("Quit button")
self.setSize(600, 400)
self.setLocationRelativeTo(None)
self.setVisible(True)
def onQuit(self, e):
System.exit(0)
if __name__ == '__main__':
Example()
Here I am just trying to make of use JTextField() so that I can get some input from the user. But after running it, the window was blank, there was no text field on the window. I ran it in sikuli r930 on windows 7. Could anyone tell me what has gone wrong??
I think there is a problem with layout in your code. Try to set some layout instead of "None". Fixed initUI function could look like this:
def initUI(self):
panel = JPanel()
panel.setLayout(FlowLayout(FlowLayout.CENTER,1,150))
self.getContentPane().add(panel)
area = JTextField('',15)
panel.add(JLabel("username:", SwingConstants.RIGHT))
panel.add(area)
self.setTitle("Quit button")
self.setSize(600, 400)
self.setLocationRelativeTo(None)
self.setVisible(True)
Additional import line is needed in this case:
from java.awt import FlowLayout

Access windows for notebook in Tkinter

I have been trying to create an open windows which asks you for username and password before opening a notebook in Tkinter, I have both, but I don't know how to put them together. In other words, what I want is to open a notebook once the username and password requested are correct.
Thank you very much in advance!
What I have done so far is as follows:
import Tkinter
from Tkinter import *
import ttk
from ttk import * #Combobox Definition
import tkMessageBox #for Welcome Message
import Tkinter as tk # For Main Frame Definition
from Tkinter import Tk, Text, BOTH, W, N, E, S
from ttk import Frame, Button, Label, Style
root = Tk()
root.title("Model A")
root.minsize(400, 220)
root.maxsize(410, 240)
# start of Notebook (multiple tabs)
notebook = ttk.Notebook(root)
notebook.pack(fill='both', expand='yes')
notebook.pressed_index = None
# create a child frame for each page
frameOne = Tkinter.Frame(notebook, bg='white',width=560, height=100)
frameOne.pack(fill='both', expand=True)
# create the pages
notebook.add(frameOne, text='Simple calculation')
#Login Starts
failure_max = 8
passwords = [('name','password')]
def make_entry(parent, caption, width=None, **options):
tk.Label(parent, text=caption).pack(side=tk.TOP)
entry = tk.Entry(parent, **options)
if width:
entry.config(width=width)
entry.pack(side=tk.TOP, padx=10, fill=tk.BOTH)
return entry
def enter(event):
check_password()
def check_password(failures=[]):
if (user.get(), password.get()) in passwords:
root.destroy()
return
failures.append(1)
if sum(failures) >= failure_max:
root.destroy()
raise SystemExit('Unauthorized login attempt')
else:
root.title('Try again. Attempt %i/%i' % (sum(failures)+1, failure_max))
parent = Tkinter.Frame(notebook, padx=10, pady=18, bg='white')
parent.pack(fill=tk.BOTH, expand=True)
user = make_entry(parent, "User name:", 16, show='')
password = make_entry(parent, "Password:", 16, show="*")
b = tk.Button(parent,borderwidth=4,text="Login",width=10,pady=8,command=check_password)
b.pack(side=Tkinter.BOTTOM)
password.bind('<Return>', enter)
#Close Application Button
def quit(root):
root.destroy()
tk.Button(root, text="Close Application", command=lambda root=root:quit(root)).pack()
#Calculation Starts
def defocus(event):
event.widget.master.focus_set()
def multiply(*args):
try:
product.set(round(float(Num_One.get())*float(Num_Two.get())))
except ValueError:
pass
Num_One = StringVar()
Num_Two = StringVar()
product = DoubleVar()
ttk.Label(frameOne, text="Select First Number:").grid(column =3, row = 0)
NumOne_Select = Combobox(frameOne, values=("1", "2", "3","4", "5"),textvariable=Num_One)
NumOne_Select.grid(column=4, row=0, columnspan="5", sticky="nswe")
Num_One.trace("w", multiply)
ttk.Label(frameOne, text="Select Second Number:").grid(column =3, row = 6 )
NumTwo_Select = Combobox(frameOne, values=("1", "2", "3","4", "5"),textvariable=Num_Two)
NumTwo_Select.grid(column=4, row=6, columnspan="5", sticky="nswe")
Num_Two.trace("w", multiply)
ttk.Label(frameOne, text = "Product:").grid(column = 3, row = 8)
ttk.Label(frameOne, textvariable=product).grid(column = 4, row = 8)
user.focus_set()
parent.mainloop()
root.mainloop()
You have several things going wrong in your code:
you're calling mainloop twice; you should only ever call it once.
you shouldn't pack or grid widgets inside the notebook. You are packing a widget and then using notebook.add; omit the pack.
you are calling destroy on the root window if the password is good. This causes your application to exit. Don't call destroy.
Normally the way this is done is that the notebook is a child of the root window, and the username/password dialog is an instance of Toplevel. You can hide the root window and pop up the dialog, and then if the user logs in, you can destroy the dialog and un-hide the main window.

In PyGTK, how do you redraw parts of a window that are obscured during a long calculation?

Below is some elementary code.
It displays a button.
Clicking the button runs a loop.
In the loop, if you obscure
the button with a window, the
obscured part will be whitish and not
redraw until after the loop.
How can I make the button redraw in the loop?
import gtk
class MyClass:
def __init__(self):
window = gtk.Window()
window.connect("destroy", gtk.main_quit)
window.set_size_request(200, 50)
table = gtk.Table()
# Add a button to the table.
button = gtk.Button("Button")
col = 0
row = 0
table.attach(button, col, col + 1, row, row + 1)
button.connect("clicked", self.clicked_event_handler)
window.add(table)
window.show_all()
def clicked_event_handler(self, button):
for i in range(10**8):
pass
if __name__ == "__main__":
MyClass()
gtk.main()
You could run the main iteration yourself
while gtk.events_pending():
gtk.main_iteration()
A long running task should be run in a thread outside of the main loop. See this for an example with pyGTK.