Arya
Arya

Reputation: 66

How to know whether a button is clicked in tkinter?

I want to perform a task if a button is clicked. How do I do this? My code is:

from tkinter import *

root = Tk()

def hey():
    if bt1 is clicked:
        #do something
    if bt2 is clicked:
        #do something

    #some piece of code

bt1 = Button(root, text = 'yes', command = hey)
bt2 = Button(root, text = 'no', command = hey)

bt1.pack()
bt2.pack()

Upvotes: 0

Views: 1668

Answers (2)

a121
a121

Reputation: 786

from tkinter import *

root = Tk()

def func():
     #common code for both buttons

def hey(arg):
    if arg == 1:
        print("button 1 used")
        func() #mention arguments if required
    elif arg == 2:
        print("button 2 used")
        func() 


bt1 = Button(root, text = 'yes', command=lambda: hey(1))
bt2 = Button(root, text = 'no', command=lambda: hey(2))
           # you can add more buttons to do the same function,use hey(n)
bt1.pack()
bt2.pack()

Upvotes: 1

Utsav Talwar
Utsav Talwar

Reputation: 85

Based on what you have shared, you can use a parameter to pass a flag in the buttons, e.g.

bt1 = Button(root, text = 'yes', command =lambda: hey(True))
bt2 = Button(root, text = 'no', command =lambda: hey(False))

And in the code, you can do,

def hey(which): # `which` decides which statement to be followed
    if which:
        #do something
    else:
        #do something

Upvotes: 1

Related Questions