Command to trigger "long click" on left mouse button - python

I searched in win32gui and PyAutoGUI some commands that make "long - click" on the left mouse button, and I didn't find anything.
I'm actually building a code that helps me to remote another pc's mouse
so i need a command that makes a long click on a mouse.
I put *** on my code so you can see the parts where I need help:
import win32api
import time
state_left = win32api.GetKeyState(0x01) # Left button down = 0 or 1. Button up = -127 or -128
while True:
a = win32api.GetKeyState(0x01)
if a != state_left: # Button state changed
state_left = a
print(a)
if a < 0:
# *** long click on left mouse button ***
print('Left Button Pressed')
else:
# *** stop click on left mouse button ***
print('Left Button Released')
time.sleep(0.001)

In theory, PyAutoGUI covers this with mouseDown & mouseUp functions.
>>> pyautogui.mouseDown(); pyautogui.mouseUp() # does the same thing as a left-button mouse click
>>> pyautogui.mouseDown() # press the left button down
>>> pyautogui.mouseUp(x=100, y=200) # move the mouse to 100, 200, then release the button up.

A solution might be:
pyautogui.dragTo(100, 200, button='left') # drag mouse to X of 100, Y of 200 while holding down left mouse button
pyautogui.dragTo(300, 400, 2, button='left') # drag mouse to X of 300, Y of 400 over 2 seconds while holding down left mouse button
pyautogui.drag(30, 0, 2, button='right') # drag the mouse left 30 pixels over 2 seconds while holding down the right mouse button

Related

how do i keep a key pressed using pyautogui?

i am very new to coding and am making a macro for a game that after seing the specified color it will move the cursor to said color.
the code goes:
from time import sleep
import pyautogui
x=1
color = (166, 166, 61)
sleep(5)
while x==1:
s = pyautogui.screenshot()
pyautogui.keyDown("space")
for x in range(1171, 1172):
for y in range(544, 990):
if s.getpixel((x, y)) == color:
pyautogui.moveTo((x,y))
pyautogui.keyUp("space")
sleep(38)
the thing is that the space bar is not held like it would be if a player held it down as the menu connected to it doesn't open. Is there any way for me to simulate pressing the space bar so that it acts like it was pressed irl?

What keysym does the <Button-1> (left mouse button )have?

I have a function:
def sound(self,event):
playsound('monkey_sound.wav', block=False)
It responds to pressing only one key - the left mouse button. I have to make it in that way, that sound will be different depending on the pressed key (left mouse button or right mouse button). But there should be only one function.
Here is fragment of my code:
class monkey:
def __init__(self, canvas):
self.canvas=canvas
self.photo = PhotoImage(file='C:\\monkey_exe\\monkey.png')
self.id=canvas.create_image(30,30,anchor=NW,image=self.photo)
self.canvas.bind_all('<Motion>', self.motion)
self.canvas.bind_all('<Button-1>', self.sound)
self.canvas.bind_all('<Button-2>', self.sound)
def motion(self,event):
canvas.coords(self.id, event.x-50, event.y-108)
def sound(self,event):
playsound('monkey_sound.wav', block=False)
So the two keys must be binded to the same function, but they must play different sounds. But I don't know keysym's of left mouse button and right mouse button.
I am unsure on what the symbol of the mouse buttons, but I found a decent alternative with using the event.num property...
def sound(self, event):
if event.num == 1: #left mouse button
playsound("monkey_sound1.wav", block=false)
elif event.num == 2: #middle mouse button
playsound("monkey_sound2.wav", block=false)
elif event.num == 3: #right mouse button
playsound("monkey_sound3.wav", block=false)
The event.num will return a number between 1-3 (unless you bind the function to another key/button).

Creating a Main Menu for connect 4 on python

I am trying to create a main menu (starting page) for a 3 player connect 4 but I am unable to create one I want 5 buttons (3 player game, 2 player game, single player, options, Quit).
Can anyone help? If possible can anyone give me example code which I could adapt to my game.
I haven't created a main menu before.
I don't mid use of tkinter or pygame.
A small example of a yellow button, that when clicked prints some text (more explanation in code comments):
import pygame
pygame.init()
screen = pygame.display.set_mode((500, 400))
clock = pygame.time.Clock()
# create the surface that will be the button
btn = pygame.Surface((300, 200))
btn.fill((255, 255, 0))
rect = btn.get_rect(center=(250, 200))
clicked = False
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
screen.fill((0, 0, 0))
# get mouse pos
mouse_pos = pygame.mouse.get_pos()
# get the state of left mouse button
left, *_ = pygame.mouse.get_pressed()
# check if mouse is in the button and if the mouse button has been clicked
# the flag `clicked` is for registering the click once when button is pressed
# otherwise it will loop again and the conditions will be true again
# you can also use the event loop above to detect whether the
# mouse button has been pressed, then the flag is not needed
if rect.collidepoint(mouse_pos) and left and not clicked:
clicked = True
print('clicked')
# reset flag
if not left:
clicked = False
# show the button
screen.blit(btn, rect)
pygame.display.update()
Useful:
pygame.Rect.collidepoint
Here’s a small example using Tkinter:
from tkinter import *
def click():
# Make another window.
top = Toplevel()
# You can add more elements here.
# Creating the Main Window
root = Tk()
root.title(“Connect 4”) # You can replace the title with your own
btn = Button(root, text=“Place Your Text”, command=click).pack()
# You can add as many of these buttons
root.mainloop()

turtle.onclick lagging 1 cycle behind

When creating a turtle onclick event my clicks lags 1 click behind.
In my example I have two buttons that adds or subtracts 1 from a value, when I click one of the buttons it does the action of the last button I pushed, not the one I just clicked.
Example:
My number is 3.
Start program.
Click "+" -> nothing happens.
Click "+" -> number becomes 4.
Click "-" -> number becomes 5.
Click somewhere blank -> number becomes 4.
Click "+" -> nothing happens.
Click somewhere blank -> number becomes 5.
Example code.
import turtle
num = 3
turtle.setup(400,500)
wn = turtle.Screen()
wn.title("None")
wn.bgcolor("black")
# Functions for what happens clicking the minus or plus button
def num_minus(xcor, ycor):
global num
if num > 1:
num = num-1
num_disp.clear()
num_disp.write("{}".format(num), align="center", font=("Arial", 26, "normal"))
print(num)
def num_plus(xcor, ycor):
global num
if num < 9:
num = num+1
num_disp.clear()
num_disp.write("{}".format(num), align="center", font=("Arial", 26, "normal"))
print(num)
# Creating minus button, left of number
minus_btn = turtle.Turtle()
minus_btn.penup()
minus_btn.color("gray")
minus_btn.shape("square")
minus_btn.goto(-30, 0)
minus_btn.onclick(num_minus)
# Creatig plus button, right of number
plus_btn = turtle.Turtle()
plus_btn.penup()
plus_btn.color("gray")
plus_btn.shape("square")
plus_btn.goto(30, 0)
plus_btn.onclick(num_plus)
# Displays the number
num_disp = turtle.Turtle()
num_disp.penup()
num_disp.color("red")
num_disp.goto(0, -20)
num_disp.write("{}".format(num), align="center", font=("Arial", 26, "normal"))
num_disp.ht()
wn.listen()
wn.mainloop()
Why are my clicks 1 click behind, and how do I fix this?
I was not able to reproduce the errant behavior you describe. Regardless, here's some possibilities to consider:
On some systems, the turtle window does not come up as the key window and you need to click on it once (anywhere) to have it receive events. You should be able to click between the turtle window and another window on your screen to see how the windows visually change as they gain, and lose, key status. If your window needs to be clicked first to receive events, then you may be miscounting that click as a button click.
Your event handlers are open to receive a new event while they are still processing a previous event. They should be disabled until they are ready for a new event to keep events from interrupting one another and messing with your count.
You instruct the turtle window to listen() to keyboard events which are not used in this interface, so don't turn that on.
Below is my rework of your code to address some of the above and restyle it -- see if it fixes any of your issues or not:
from turtle import Screen, Turtle
FONT_SIZE = 26
FONT = ('Arial', FONT_SIZE, 'normal')
number = 3
# Functions for what happens when clicking the minus or plus button
def number_minus(x, y):
global number
minus_button.onclick(None) # disable handler inside handler
if number > 1:
number -= 1
number_display.clear()
number_display.write(number, align='center', font=FONT)
minus_button.onclick(number_minus) # reenable handler on exit
def number_plus(x, y):
global number
plus_button.onclick(None)
if number < 9:
number += 1
number_display.clear()
number_display.write(number, align='center', font=FONT)
plus_button.onclick(number_plus)
screen = Screen()
screen.setup(400, 500)
screen.bgcolor('black')
# Displays the number
number_display = Turtle()
number_display.hideturtle()
number_display.color('red')
number_display.penup()
number_display.sety(-FONT_SIZE/2)
number_display.write(number, align='center', font=FONT)
# Creating minus button, left of number
minus_button = Turtle()
minus_button.shape('triangle')
minus_button.color('gray')
minus_button.left(30)
minus_button.penup()
minus_button.setx(-30)
minus_button.onclick(number_minus)
# Creatig plus button, right of number
plus_button = Turtle()
plus_button.shape('triangle')
plus_button.color('gray')
plus_button.right(30)
plus_button.penup()
plus_button.setx(30)
plus_button.onclick(number_plus)
screen.mainloop()

Check for mouse press while mouse moves

I'm making a simple program that randomly moves my mouse to farm hours on sites like VHL. I want to add a section of code that stops the code from running when the mouse button is pressed.
So far I have this:
# imports
import random
import time
import pyautogui
# screen resolution - 2256, 1504
while True: # constantly runs, constantly updates variables
# vars that need to update part
posX = random.randint(0, 2256) # get a random x coordinate
posY = random.randint(0, 1504) # get a random y coordinate
randDuration = random.randint(2, 10) # get a random duration for mouse movement
randSleep = random.randint(5, 100) # get a random sleep time
# code part
pyautogui.moveTo(posX, posY, randDuration) # moves cursor to random coordinates from defined variables
print(f"Cursor moved to x:{posX} y:{posY} in {randDuration} seconds!")
time.sleep(randSleep)
from pynput.mouse import Listener
def is_clicked(x, y, button, pressed): # function that stops code after mouse1 is pressed
if pressed:
exit()
with Listener(on_click=is_clicked) as listener:
listener.join()
Everything works fine, but I want to be able to stop the program while the mouse is moving. In other words, while the line below runs:
pyautogui.moveTo(posX, posY, randDuration)
I want to simultaneously check if the mouse 1 button is being pressed.
Please let me know if you need any clarification. Thanks for the help.

Categories