Stopping running while loop if conditions are met - python

The code below is intended to print out the contents of arrays, until either the mouse (left click) is released, or the end of the array is reached. How would I stop the while loop in the function logging_mouse, once the mouse is released?
running = False
i = 0
delta_x=[1,2,3]
delta_y = [3,2,1]
def logging_mouse(running,i):
while (running and i < len(delta_x)):
print(delta_x[i],delta_y[i])
i = i+1
running = False
def on_click(*args):
global running
global i
print(running)
i = args[3]
print(i)
if args[-1]:
if not running:
running = True
threading.Thread(target=logging_mouse(running,i)).start()
else:
running = False
i = 0
with Listener(on_click=lambda event1,event2,event3,event4: on_click(event1,event2,event3,i,event4)) as listener:
listener.join()

you need to actually use the args to the on_click function... you can detect whether or not a button is pressed down or released, the signature for on_click should be on_click(x,y,button,pressed) where x and y represent the location of the mouse press, button says which button was pressed, and pressed is True if the button is down and False if it was released

Related

create a button that can only be pressed once

i am trying to create a button that can only be pressed once for a game in python but i cant figure out how to set a variable that works in the def and does not change every time the function is run.
tut = turtle.Screen()._root
def bt1():
pressed = 1
x_turn = True
if (pressed == 1):
if (x_turn is True):
print("this button has not been pressed as player1")
x_turn == False
pressed = 0
else:
print ("this button has not been pressed as player2")
pressed = 0
x_turn == True
else:
print("this button has been pressed")
photo1 = Image.open(r"C:\image.png")
resize_photo1 =photo1.resize((50,50), Image.ANTIALIAS)
print_photo1 = itk.PhotoImage(resize_photo1)
Button(tut, image= print_photo1,command=bt1).pack(side= LEFT)
what i am gathering is that when this button is pressed you want it to set pressed to 0 so it can not run again but since you put the variable at the top every time the button is bressed it will set it to 1. to fix this all you want to do is....
tut = turtle.Screen()._root
global pressed
pressed = 1
global x_turn
x_turn = True
def bt1():
if (pressed == 1):
if (x_turn is True):
print("this button has not been pressed as player1")
x_turn == False
pressed = 0
This might work let me know if it does
x_turn = True
Try using this :
x_turn == True
I think here you’re missing the equals to sign and that’s why it is creating a problem.

Monitoring mouse coordinate while a key is pressed

I am trying to make a windows analog of the Chat-wheel from Dota 2 or Battlefield with some fast commands like this.
How it should be:
While the G-key is pressed - the wheel with some sections appears at the centre of the screen, with the mouse centered on it and if I move the mouse to side_1 and then release the G-key -> func_1 executes.
If it was on side_2 -> func_2.
If I release the G-key at the centre -> wheel disappears and nothing happens.
So to monitor the X Y coordinates of the mouse I use following code:
from pynput import mouse
def on_move(x, y):
print(x, y)
# Collect events until released
with mouse.Listener(on_move=on_move) as listener:
listener.join()
It is spamming coordinates when I move the mouse.
But I am stuck in the part where i need:
to start the listener from another .py file and take these coordinates for the visual part of the program (like highlight the side of the wheel with command descriptions),
to close the listener from another .py file and take the last coordinates of the mouse when the G-key is released to compare with tge range of coordinates prescribed for functions.
You want something like this:
from pynput import mouse, keyboard
import time
def on_press(key):
print("pressed {}".format(key))
def on_release(key):
print("released {}".format(key))
def on_move(x,y):
print((x,y))
mouse_listener = mouse.Listener(
on_move=on_move)
mouse_listener.start()
key_listener = keyboard.Listener(
on_press=on_press,
on_release=on_release)
key_listener.start()
# prevent the script from exiting immediately
time.sleep(10)
import time
import keyboard
from pynput.mouse import Controller
def get_xy():
mouse = Controller()
mouse_coord = str(mouse.position)
mouse_coord = mouse_coord.replace("(", "")
mouse_coord = mouse_coord.replace(")", "")
mouse_coord = mouse_coord.replace(",", "")
mouse_coord = mouse_coord.split(" ")
mouse_x = int(mouse_coord[0])
mouse_y = int(mouse_coord[1])
print(mouse_x, mouse_y)
while True:
if keyboard.is_pressed('b'):
get_xy()
time.sleep(0.01)
Output example: 654 326

How do i detect which specific button in my controller is being released in pygame

i am trying to detect which button is being pressed from my controller and when it is released.
This is how far i have managed to get.
import pygame
pygame.init()
j = pygame.joystick.Joystick(0)
j.init()
try:
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.JOYBUTTONDOWN:
if j.get_button(1):
print("x")
elif j.get_button(2):
print("a")
elif event.type == pygame.JOYBUTTONUP:
print("button released")
except KeyboardInterrupt:
print("EXITING NOW")
j.quit()
i am new to programming and i dont entirely understand this piece of code.
this detects if x or a is being pressed and if any button is being released. I want it to detect if x or a is being pressed and when they are released.
Thanks for reading!
pygame.event.get() returns a list of events(events are a type of structure/object of pygame generated when the user does something moves mouse / presses buttons e.t.c.).then for each of those events you check if the they are the event you want(pygame.JOYBUTTONDOWN or event.type,pygame.JOYBUTTONUP).
you can only check if a button is pressed and then see which button is pressed.
if event.type == pygame.JOYBUTTONDOWN:
if j.get_button(1):
print("x")
elif j.get_button(2):
print("a")
to see when buttons get released best way i can think off is having a list of Button Status .When the status for a button changes you do something .
ButtonStatus[2];
ButtonStatus[0]=get_button(1);#a
ButtonStatus[1]=get_button(2);#x
if event.type == pygame.JOYBUTTONUP:
if ButtonStatus[0]!=get_button(1)
#status changed do yr code for button release a
pass;
if ButtonStatus[1]!=get_button(2)
#status changed do yr code for button release b
pass;
above code is a sample not actually compiled . general idea is to check when a button is released,check which button changes status and execute code accordingly.
So, i coded what i needed with the help of the other answers!
import pygame
pygame.init()
j = pygame.joystick.Joystick(0)
j.init()
r = 2
t = 5
b = 1
x = 3
try:
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.JOYBUTTONDOWN:
if j.get_button(1):
print("B")
b = 2
elif j.get_button(2):
print("X")
x = 5
elif event.type == pygame.JOYBUTTONUP:
if b == r :
print("b2")
b = 1
if x == t:
print("x2")
x = 3
except KeyboardInterrupt:
print("EXITING NOW")
j.quit()
This isn't robust in any way. You need to make new strings for every button you need.
You do that by copying the button with the biggest variables and just adding 3 to every variable in the code you coppied. Please answer the original post if you can give a better answer (which probably exists).Also, when u press multiple buttons at the same time and u release atleast one it thinks you have realeased all of them.

How to trigger a function by clicking the left mouse click in Python?

I want to start off by saying that I am new to Python so I am sorry if this question is going to sound stupid to you.
I am just looking for an easy way to trigger a function whenever I press the left click of my mouse.
Could anyone illustrate me how to achieve this? Examples are greatly appreciated.
My code now:
import win32api
import win32con
import time
from random import randint
import pythoncom, pyHook
def OnMouseEvent(event): #triggers mouseClick function
mouseClick(event)
return True
def mouseClick(event):
if event.MessageName == "mouse left up": # makes sure that's the event I'm looking for
a = True # disables hm.MouseAll
return a
time.sleep(0.01)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
time.sleep(0.005)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
time.sleep(0.01)
a = False # enables hm.MouseAll back
return a
a = False
# create a hook manager
hm = pyHook.HookManager()
# set the hook
hm.HookMouse()
# wait forever
pythoncom.PumpMessages()
# watch for all mouse events
while True:
if a == False:
hm.MouseAll = OnMouseEvent # Triggers OnMouseEvent function
else:
pass
What I understand is that you already have a function ready. I would use Pygame package for this.
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
nameoffunction()
changing the number 1 in event.button == 1: will change that what mouse button is clicked.
EDIT 1
run = 1
while run == 1:
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
print("Message")
PyGame requires a window so if you just want to test a click I would then use...
EDIT 2
if win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0):
print("Message")
x,y = x and y starting coordinates for box corner
0,0 = Other corner for box (i think)
know if mouse is inside of the "box" and you click it should work
(I haven't got win32api installed so haven't ran any tests with this)

python pygame how to debounce a button?

so im building a pi based robot.
It uses a ps3 controller for input. When the X button is pressed, it takes a photo. For some reason, it takes around 5 shots at a time. Is there a way to bounce the input so it only recognises one press?
I'm assuming it's registering multiple presses each time... Part of the code is attached, but I must state most of it is used from piborg.org
joystick = pygame.joystick.Joystick(0)
button_take_picture = 14 # X button
while running:
# Get the latest events from the system
hadEvent = False
events = pygame.event.get()
# Handle each event individually
for event in events:
if event.type == pygame.QUIT:
# User exit
running = False
elif event.type == pygame.JOYBUTTONDOWN:
# A button on the joystick just got pushed down
hadEvent = True
elif event.type == pygame.JOYAXISMOTION:
# A joystick has been moved
hadEvent = True
if hadEvent:
if joystick.get_button(button_take_picture):
take_picture()
What seems to be happening is that the X button stays down for multiple frames. Some other events might happen during this time, causing a call to take_picture() in your code for every frame. To fix this, you can either call take_picture() only on JOYBUTTONUP (when the button is released), or move the if joystick.get_button(button_take_picture) part to inside the pygame.JOYBUTTONDOWN section.
Alternatively, you could use another variable to indicate whether the picture was already taken, like this:
picture_was_taken = False
while running:
hadEvent = False
events = pygame.event.get()
for event in events:
...
if event.type == pygame.JOYBUTTONUP:
if not joystick.get_button(button_take_picture)
picture_was_taken = False
...
if hadEvent:
if joystick.get_button(button_take_picture) and not picture_was_taken:
take_picture()
picture_was_taken = True

Categories

Resources