I am not aware of any internal tkinter method to check if a button is pressed.

However you could connect the Button with a function that changes the value of a global variable, like in the following:

from Tkinter import *

master = Tk()

def callback():
    global buttonClicked
    buttonClicked = not buttonClicked 


buttonClicked  = False # Bfore first click

b = Button(master, text="Smth", command=callback)
b.pack()

mainloop()

The code, changes the variable value from False to True (or reverse) every time you press the button.

Answer from Charalamm on Stack Overflow
🌐
Python Forum
python-forum.io › thread-2442.html
Conditional Button Press
I am looking to make a while loop break upon button press but I'm not sure how to do so. I assume it would be with a conditional statement but the syntax is foreign to me. A pseudocode example would be as follows: while True: - statement if *Butt...
Discussions

tkinter - Checking if a button has been pressed in python? - Stack Overflow
Code: import sys from tkinter import * credit = 0 coins = 0 choice = 0 credit1 = 0 coins = 0 prices = [200,150,160,50,90] item = 0 i = 0 temp=0 n=0 choice1 = 0 choice2 = 0 credit1 = 0 coins = 0 ... More on stackoverflow.com
🌐 stackoverflow.com
November 29, 2016
On python, how do I determine which button was clicked - Stack Overflow
How would I run an if statement to determine which button was clicked? I've been looking around, but I am new to Tkinter and I'm not too sure what I'm supposed to do. self.button1 = Tkinter.Bu... More on stackoverflow.com
🌐 stackoverflow.com
python - how to check if button is clicked on tkinter - Stack Overflow
This mainloop basically checks if there is an event, does what it is told to do when this event happens, updates the window, repeat. So all you have to do is tie your function to the button press event, which you do with the command=. Do keep in mind that returning values from a button press ... More on stackoverflow.com
🌐 stackoverflow.com
August 9, 2018
How do you say "If button is pressed, then do this" in python tkinter? - Stack Overflow
I am trying to say "if the thing that you are trying to press equal for is an integer, then do what i have, but if it is a string, then print either "cos(whatever number)", "tan(whatever number)", ... More on stackoverflow.com
🌐 stackoverflow.com
May 22, 2017
🌐
Microsoft MakeCode
makecode.microbit.org › reference › input › button-is-pressed
Button Is Pressed
basic.forever(() => { let pressed = input.buttonIsPressed(Button.A) if (pressed) { // this part runs if the A button is pressed basic.showNumber(1) } else { // this part runs if the A button is *not* pressed basic.showNumber(0) } })
🌐
TutorialsPoint
tutorialspoint.com › determine-which-button-was-pressed-in-tkinter
Determine which Button was pressed in Tkinter
May 25, 2021 - #Import the required libraries from tkinter import * from tkinter import ttk #Create an instance of Tkinter Frame win = Tk() #Set the geometry win.geometry("700x250") # Define function to get the information about the Button def get_button(t): print(t) #Create Button Object b1= ttk.Button(win, text= "Button-1", command= lambda t= "Button-1 Clicked": get_button(t)) b1.place(relx= .46, rely= .5, anchor= CENTER) b2= ttk.Button(win, text= "Button-2", command= lambda t= "Button-2 Clicked": get_button(t)) b2.place(relx= .58, rely= .5, anchor= CENTER) win.mainloop()
🌐
YouTube
youtube.com › robotics back-end
Detect when a Push Button is Pressed with Python - Raspberry Pi Tutorial for Beginners 9 - YouTube
In this Raspberry Pi tutorial you will learn how to read a push button’s state with Python code.🔥 Complete Raspberry Pi Course for Beginners 👉 https://rbck...
Published   June 20, 2022
Views   2K
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-check-which-button-was-clicked-in-tkinter
How to check which Button was clicked in Tkinter ? - GeeksforGeeks
July 29, 2024 - When the button is pressed, Tkinter calls that function or method. Note:Â For more reference, you can read our article, What is WidgetsPython Tkinter OverviewPytho · 5 min read Python | Tkinter ttk.Checkbutton and comparison with simple Checkbutton
Find elsewhere
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 400766 › how-to-tell-if-a-button-is-clicked
python:tkinter - How to tell if a button is clicked | DaniWeb
September 21, 2015 - python:tkinter · 0 0 · Reply with Quote · Share · Edited 13 Years Ago by Koreakid101 because: n/a · 3 Contributors · 4 Replies · 9K Views · 1 Day Discussion Span · Latest Post 13 Years Ago Latest Post by TrustyTony · In Tkinter you do not poll a button to see if it was clicked; you attach a callback with the button’s command. That callback is your signal that the note was pressed.
🌐
CodeProject
codeproject.com › Questions › 5328169 › How-do-I-check-if-button-is-being-held-Python
How do I check if button is being held (Python) - CodeProject
March 23, 2022 - Free source code and tutorials for Software developers and Architects.; Updated: 17 Apr 2023
🌐
Stack Overflow
stackoverflow.com › questions › 33284786 › how-do-you-say-if-button-is-pressed-then-do-this-in-python-tkinter
How do you say "If button is pressed, then do this" in python tkinter? - Stack Overflow
May 22, 2017 - from tkinter import* root = Tk() def btnPress(num): global result result = result+str(num) equation.set(result) def equalPress(): global result total = str(eval(result)) equation.set(total) result = total def clear(): global result result = "" equation.set("") result = "" btnWidth = 5 equation = StringVar() equation.set("Enter your equation.") calculation = Label(root, textvariable = equation, width = btnWidth*4) calculation.grid(row = 0, column = 0, columnspan = 4) Button0 = Button(root, text = "0", command=lambda:btnPress(0), width = btnWidth) Button0.grid(row = 4, column = 2) Button1 = Butt
🌐
Kodi Forum
forum.kodi.tv › showthread.php
detect button press and use it in a Python script?
July 26, 2020 - I've never worked with Python inputs library. From a Kodi addon perspective, an addon works with Kodi actions that can be mapped do different physical controller events, e.g. keypresses, touchscreen gestures etc. So I have no idea how to intercept actual controller events from an addon. ... R.O.H. Fan Posts: 580 ... R.O.H. Fan Posts: 580 ... (2020-08-09, 20:41)3000 Wrote: I'm pressing RB (right bumper) on my Xbox controller what action is mapped to this button? if you map it to RunScript() (as suggested in the first reply) you can have your addon execute this action + whatever code you need to toggle those listening modes on your receiver.
🌐
Stack Overflow
stackoverflow.com › questions › 41396186 › if-loop-in-tkinter-button-pressed
if statement - If loop in tkinter - button pressed - Stack Overflow
from tkinter import * class Player: N = 0 def __init__(self, name, points): # instance variables goes here self.name = name self.score = points # increment class variable Player.N = Player.N+1 class G_501: def __init__(self, players=[]): self.NoPlayers = len(players) print("Number of players",self.NoPlayers) Spillere = [] Score = [] Runde = 0 for i in range(0, len(players)): P = Player(players[i], 501) print("Player", Player.N, P.name, "- Point:", P.score) Spillere.append(P.name) Score.append(P.score) Score = list(map(int, Score)) root = Tk() c = [False] def half_bull(c, event=None): c.append(True) return c b1 = Button(root, text="Half Bull", bg="green", fg="black", command=lambda c=c: half_bull(c)) b1.pack() print(c) if c[-1] == True: print("Fedt") root.mainloop() S = G_501(["Chr"])
🌐
BBC micro:bit
microbit-micropython.readthedocs.io › en › latest › tutorials › buttons.html
Buttons — BBC micro:bit MicroPython 1.1.1 documentation
Often you need your program to hang around waiting for something to happen. To do this you make it loop around a piece of code that defines how to react to certain expected events such as a button press. To make loops in Python you use the while keyword. It checks if something is True.
🌐
All About Circuits
forum.allaboutcircuits.com › home › forums › embedded & programming › programming & languages
Python tkinter detecting which button is pressed | All About Circuits
November 26, 2020 - for x in range(0,len(self.Serial_order)):# CREATE A LIST OF ARRAYS BASED ON CURRENT CSV FILE AND DISPLAY self.serial_entries.append(tk.StringVar()) self.serial_entries[x].set(self.Serial_order[x]) self.order_entries.append(tk.StringVar()) self.order_entries[x].set(self.Picking_order[x]) self.delete_entry_button.append(tk.Button(self.innercanvas,foreground="green",text="Delete entry",command =lambda: self.delete_row_of_entry(x))) code_labels_entry = tk.Entry(self.innercanvas,width=5,textvariable=self.serial_entries[x]) order_labels_entry = tk.Entry(self.innercanvas,width=5,textvariable=self.ord
🌐
Stack Overflow
stackoverflow.com › questions › 41222411 › checking-if-a-button-was-clicked
python - Checking if a Button was clicked - Stack Overflow
December 20, 2016 - The hello() # function is defined above. self.button.connect("clicked", self.hello, None) self.window.add(self.button) self.button.show() self.window.show() def main(self): # All PyGTK applications must have a gtk.main(). Control ends here # and waits for an event to occur (like a key press or mouse event). gtk.main() if __name__ == "__main__": hello = HelloWorld() hello.main()
Top answer
1 of 2
3

Depending on how your circuit is wired you should use

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)

inputPin = "YOUR_PIN_GOES_HERE"
GPIO.setup(inputPin,GPIO.IN,pull_up_down=GPIO.PUD_UP)

def buttonPress(channel):
     #stuff

def buttonRelease(channel):
     #stuff


GPIO.add_event_detect(channel,GPIO.RISING,callback=buttonPress)
#OR
GPIO.add_event_detect(channel,GPIO.FALLING,callback=buttonRelease)

while(1):
      keypressed = raw_input('Press q to quit: ')
      if keypressed == 'q':
           break
      elif keypressed == 'SOME OTHER KEY':
           #code for some other thing
      else
           print("Unknown input")

These are events that will be trigged where there is a change on your input pin. Your raw_input can still handle whatver code you want because the event loop is running in the background.

Pulled from here

Edits: put the event defs above event declaration because I am teh dumb

While(1)'s are ugly. For the sake of staying a loop this should suffice though. Essentially this will run the keyboard input loop until you hit q. Use the elifs to handle other inputs. The else will capture unknown input and provide feedback. The break statment will boot the program out of the while loop and will reach the end of code and terminate.

Should you feel fancy and want to handle a lot of input I would look to use what other languages have a switch statement to clean up a bunch of elifs

Oh and standard warranty applies, I may have missed a tab or : here and there.

2 of 2
1

Your Python module will offer GPIO callbacks. Generally you specify

  • a GPIO
  • whether you are interested in rising edges (0->1), falling edges (1->0), or both edges
  • and a function to be called when the event happens

The specified function will be called asynchronously to the main thread, i.e. it will still be called even if the main thread is waiting in a raw_input.

Generally you would use global variables to pass state information between the callback and main thread.