To Detect Button Press In Python Tkinter Module

To Detect Button Press In Python Tkinter Module

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)


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

I think that you could make a function to change the value of buttonClicked, and, when the button is clicked, it executes that function (whose only purpose is to change the value of buttonClicked).

The complete code could go as follows:

from tkinter import *
buttonClicked = False
def changeValue():
    if buttonClicked:
    if not buttonClicked:
tk = Tk()
btn = Button(tk, text=Put whatever text you want here, to tell the person what pressing the button will do, command=changeValue())

If this answer help, I would appreciate you tell me! :).

This is a changed/edited version, with a loop for logic that changes the value of buttonClicked. In the part of code that says if not buttonClicked: you could change to an else: statement. @

To Detect Button Press In Python Tkinter Module

Try this:

from tkinter import *
value = 1
def change_value():
       global value
       value -= 1
       if value == 0:
                 print(button pressed)
                 value = 1
tk = Tk()
btn = Button(tk, text=your_text, command=change_value)

Leave a Reply

Your email address will not be published. Required fields are marked *