How to add a back button in pygame - python

So I decided to make a back button for by game in pygame because it has a main menu and lots of other menus within it(such as a help menu). I already have the code for making a button, but all I need is some kind of function that allows the button function like a back button.
Here is my button function that I normally use to make a button:
def button(x, y, w, h, inactive, active, action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + w > mouse[0] > x and y + h > mouse[1] > y:
gameDisplay.blit(active, (x, y))
if click[0] == 1 and action is not None:
action()
else:
gameDisplay.blit(inactive, (x, y))
Here's what each parameter in button() means:
x: x-coordinate of the button
y: y-coordinate of the button
w: width of button image
h: height of button image
active: picture of button when the mouse is hovering over it
inactive: picture of button when it is idle
action: the function to be executed when the button is clicked(this should be a function)
Thanks in advance!

What I really recommend is the pygame-menu package for creating menu. It has quite a big variety of widgets and working workflow. Probably based on their github you might find what you are looking for.
pygame-menu github
I don't understand what is the difference between yours 'back button' and 'normal button', but this page might help.

If you mean a back button which lets you get back to the main menu then you just need to reference the main menu function as the action:
backButton = button(x, y, w, h, inactive, active, mainMenu()):

Related

stop canvas shape from following cursor after a mouse click

I am making a GUI to draw weighted graphs using Tkinter, so I made a button that when clicked creates a circle(graph vertex) using canvas. then the circle should follow the cursor to any position on the canvas and stop when the mouse clicks.
I managed to make the the circle follow the cursor, but I have no idea how to make it stop following.
this is the function I made
def buttonClick():
def Mouse_move(event):
x,y = event.x , event.y
canvas.moveto(vertex,x,y )
vertex= canvas.create_oval(650, 100, 750, 200)
canvas.bind("<Motion>", Mouse_move)
You can bind the mouse click event <Button-1> and unbind the <Motion> event in the callback:
def buttonClick():
def mouse_move(event):
x, y = event.x, event.y
canvas.moveto(vertex, x, y)
def mouse_click(event):
canvas.unbind("<Motion>")
vertex = canvas.create_oval(650, 100, 750, 200)
canvas.bind("<Motion>", mouse_move)
canvas.bind("<Button-1>", mouse_click)

How to draw a square on canvas when he user clicks 2 locations with tkinter

I am writing an app where the user can "paint" a canvas and now I want to add support for shapes.
I have a canvas called paint_canvas and I want to draw a shape between the 2 points the user clicks
def draw_square(event):
x1 = event.x
y1 = event.y
# now I want to get the next two points the user clicks
# how???????
paint_canvas = Canvas(root)
paint_canvas.bind('<Button-3>', draw_square)
You can make two events,
One for the press event ans one for release.
In the first event you store x and y mouse position in another scope (startx , starty)
And in the second event you store mouse position store x and y mouse position in another scope (endx, endy) and then draw your shape with this coordinates
See : https://docstore.mik.ua/orelly/other/python/0596001886_pythonian-chp-16-sect-9.html
And : https://www.codegrepper.com/code-examples/delphi/how+to+draw+rectangle+in+tkinter
If you want to show your rect animation you can use Motion events
Mouse Position Python Tkinter
You don't have to work with double-events. You can just as well store the previously clicked coordinates and draw a rectangle (and reset the previously stored coordinates) as soon as you have two clicks:
from tkinter import *
def draw_square(event):
x1 = event.x
y1 = event.y
w = event.widget ## Get the canvas object you clicked on
if w.coords == None:
w.coords = (x1,y1)
else:
w.create_rectangle(w.coords[0],w.coords[1],x1,y1,fill="#ff0000")
w.coords = None
root = Tk()
paint_canvas = Canvas(root,width=400,height=400,bg="#ffffff")
paint_canvas.pack()
paint_canvas.bind('<Button-3>', draw_square)
paint_canvas.coords=None
root.mainloop()
You could even create a temporary point to mark the first click, which may then be removed as soon as you hit the second one. This point (w.temp in the example below) can also be an attribute of the canvas, so you can access it easily via the click:
def draw_square(event):
x1 = event.x
y1 = event.y
w = event.widget ## Get the canvas object you clicked on
if w.coords == None:
w.coords = (x1,y1)
w.temp = w.create_oval(x1-1,y1-1,x1+1,y1+1,fill="#00ff00")
else:
w.create_rectangle(w.coords[0],w.coords[1],x1,y1,fill="#ff0000")
w.delete(w.temp)
w.coords = None

python - How to recognize images and click on them

I would like to make a script that clicks on images depending on what is asked, it needs to go trough a list of images. so for example if the user is asked by the program to click on the green circle:
question_list = greencircle, redcircle, bluesquare, redtriangle
if(greencircle == greencircle.png){
pyautogui.click(greencircle.png)
}
could someone help with this?
PyAutoGUI has a built in function called locateOnScreen() which returns the x, y coordinates of the center of the image if it can find it on the current screen (it takes a screenshot and then analyzes it).
The image has to match exactly for this to work; i.e. if you want to click on a button.png that button picture has to be the same exact size / resolution as the button in your windows for the program to recognize it. One way to achieve this is to take a screenshot, open it in paint and cut out only the button you want pressed (or you could have PyAutoGUI do it for you as I'll show in a later example).
import pyautogui
question_list = ['greencircle', 'redcircle', 'bluesquare', 'redtriangle']
user_input = input('Where should I click? ')
while user_input not in question_list:
print('Incorrect input, available options: greencircle, redcircle, bluesquare, redtriangle')
user_input = input('Where should I click?')
location = pyautogui.locateOnScreen(user_input + '.png')
pyautogui.click(location)
The above example requires you to already have greencircle.png and all the other .png in your directory
PyAutoGUI can also take screenshots and you can specify which region of the screen to take the shot pyautogui.screenshot(region=(0, 0, 0, 0)) The first two values are the x,y coordinates for the top left of the region you want to select, the third is how far to the right(x) and the fourth is how far down (y).
This following example takes a screenshot of the Windows 10 Logo, saves it to a file, and then clicks on the logo by using the specified .png file
import pyautogui
pyautogui.screenshot('win10_logo.png', region=(0, 1041, 50, 39))
location = pyautogui.locateOnScreen('win10_logo.png')
pyautogui.click(location)
You also don't have to save the screenshot to a file, you can just save it as a variable
import pyautogui
win10 = pyautogui.screenshot(region=(0, 1041, 50, 39))
location = pyautogui.locateOnScreen(win10)
pyautogui.click(location)
Making a program detect if a user has clicked in a certain area (let's say, the windows 10 logo) would require another library like pynput.
from pynput.mouse import Listener
def on_click(x, y, button, pressed):
if 0 < x < 50 and 1080 > y > 1041 and str(button) == 'Button.left' and pressed:
print('You clicked on Windows 10 Logo')
return False # get rid of return statement if you want a continuous loop
with Listener(on_click=on_click) as listener:
listener.join()
PUTTING IT ALL TOGETHER
import pyautogui
from pynput.mouse import Listener
win10 = pyautogui.screenshot(region=(0, 1041, 50, 39))
location = pyautogui.locateOnScreen(win10)
# location[0] is the top left x coord
# location[1] is the top left y coord
# location[2] is the distance from left x coord to right x coord
# location[3] is the distance from top y coord to bottom y coord
x_boundary_left = location[0]
y_boundary_top = location[1]
x_boundary_right = location[0] + location[2]
y_boundary_bottom = location[1] + location[3]
def on_click(x, y, button, pressed):
if x_boundary_left < x < x_boundary_right and y_boundary_bottom > y > y_boundary_top and str(button) == 'Button.left' and pressed:
print('You clicked on Windows 10 Logo')
return False # get rid of return statement if you want a continuous loop
with Listener(on_click=on_click) as listener:
listener.join()

Command to trigger "long click" on left mouse button

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

python pyglet on_mouse_press

I'm trying to make a simple GUI using pyglet.
Here is my code:
button_texture = pyglet.image.load('button.png')
button = pyglet.sprite.Sprite(button_texture, x=135, y=window.height-65)
def on_mouse_press(x, y, button, modifiers):
if x > button and x < (button + button_texture.width):
if y > button and y < (button + button_texture.height):
run_program()
The problem
The "button.png" is displayed as the red box with "Click" inside. and is supposed to start run_program(). But currently the yellow in the bottom left is the place i have to click to initiate run_program().
You are comparing the button (the key-code) with the X/Y coordinates. This happens, because the function parameter button shadows your global variable. Also, you should use the buttons x, y, width and height attributes.
button_texture = pyglet.image.load('button.png')
button_sprite = pyglet.sprite.Sprite(button_texture, x=135, y=window.height-65)
def on_mouse_press(x, y, button, modifiers):
if x > button_sprite.x and x < (button_sprite.x + button_sprite.width):
if y > button_sprite.y and y < (button_sprite.y + button_sprite.height):
run_program()
I renamed your global variable button with button_sprite to avoid the name collision.

Categories