Checking If a Button Has Been Pressed in Python

How to check if a button is pressed while running a program in python

Here is something you can try. The main function is printing a number every second, and you can interrupt it by typing "s" + the Enter key :

import threading
import time

a = True

def main():
for i in range(10):
if a:

def interrupt():
global a # otherwise you can only read, and not modify "a" value globally
if input("You can type 's' to stop :") == "s":
print("interrupt !")
a = False

t1 = threading.Thread(target=main)

How check, if button pressed twice?

You're nearly there. Just use an if/else block and set press to True after printing:

import pygame
screen = pygame.display.set_mode((200, 200))
run = True
press = False

while run:
for e in pygame.event.get():
if e.type == pygame.QUIT:
run = False
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_RETURN:
if not press:
print('more than once')
press = True

screen.fill((30, 30, 30))

How to confirm if user has pressed on a button in pysimplegui

You can use variables or attribute button.metadata to record the state clicked for buttons. Initial value for each button is set by option metadata=False in sg.Button means not yet clicked. When button clicked, button.metadata will be set to True, it means this button clicked.

Here show the way to record the clicked state in button.metadata.

import PySimpleGUI as sg

items = [
"Automobile", "Chemical", "Engineering/Consulting", "FMCG",
"Healthcare/Hospitality", "Infrastructue", "IT/Comm/DC", "Manufacturing",
"Mines", "Energy/Oil & Gas", "Pharma", "Retail", "Cement",
length = len(items)
size = (max(map(len, items)), 1)

sg.set_options(font=("Courier New", 11))

column_layout = []
line = []
num = 4
for i, item in enumerate(items):
line.append(sg.Button(item, size=size, metadata=False))
if i%num == num-1 or i==length-1:
line = []

layout = [
[sg.Text('Choose the Industry')],
[sg.Text('Enter Observation/Recommendation: ', size =(26, 1)), sg.InputText()],
[sg.Button("Predict Risk", bind_return_key=True)],
[sg.Text('If the above prediction is correct select \'yes\' else select the correct risk.')],
[sg.Button("Exit"),sg.Button("Clear Fields")]

window=sg.Window("Risk Predictor", layout, use_default_focus=False, finalize=True)
for key in window.key_dict: # Remove dash box of all Buttons
element = window[key]
if isinstance(element, sg.Button):

while True:

event, values =

if event in (sg.WIN_CLOSED, 'Exit'):
elif event in items:
window[event].metadata = True
elif event == "Predict Risk" and window["Mines"].metadata:
print("Predict Risk for Mines")


How do I check if a key has been pressed in TKinter outside the window?

You can register a callback whenever a key is pressed using .on_press() from keyboard module.

Below is an example:

import tkinter as tk
import keyboard

def on_key(event):
if == "tab":
# clear the label after 100ms
root.after(100, lambda: key_label.config(text=""))

root = tk.Tk()
key_label = tk.Label(root, width=10, font="Arial 24 bold")
key_label.pack(padx=100, pady=50)


Python Kivy: How to check if a button is clicked or not?

Your add() method is using self.i, which will be the last value that self.i was set to in the __init__() method (2). So you just need to modify your add() method to something like:

def add(self, button):
id_of_button_pressed =

How to detect what button was clicked? (Pynput)

From the Documentation Here

from pynput import mouse

def on_move(x, y):
print('Pointer moved to {0}'.format(
(x, y)))

def on_click(x, y, button, pressed):
print(button) # Print button to see which button of mouse was pressed
print('{0} at {1}'.format(
'Pressed' if pressed else 'Released',
(x, y)))

# Collect events until released
with mouse.Listener(
) as listener:

# ...or, in a non-blocking fashion:
listener = mouse.Listener(on_click=on_click)

As you can see, the button parameter in the function on_click tells you which button was pressed.


Here is how you may handle action based on which button of the mouse was pressed

 def on_click(x, y, button, pressed):
btn =

if btn == 'left':
print('Left if Pressed')
# ====== < Handle Pressed or released Event ====== > #
if pressed:
print('Do somethin when Pressed with LEft')
print('LEFT is Released')
elif btn == 'right':
print('Right BTN was pressed ')
# ====== < Handle Pressed or released Event ====== > #
if not pressed:
print('right Button is released')

Related Topics

Leave a reply