How to call a function on button click.


Here we will learn how to assign an action to button. 
To assign action, command option needs to be used. A value (method / function) assigned to command will be triggered on button click.

below is the code to destroy the main window on click, GUI will look like as above image


 command = action to perform


to call a function,  function  needs to assign to command option. 

IMPORTANT : 

function without parameters can be assigned directly to option command

function with parameters needs to call as lambda so that it get called on click, if a parameterised method / function is assigned without lambda, application will not wait for click on button and directly the function will get called.


#project to destroy window

try:
from Tkinter import *
except:
from tkinter import *

def destroy_win(mw1):
mw1.destroy()
mw.destroy()


def display_message():
mw1 = Tk()
mw1.geometry(
"300x50+130+120")
mw1.title(
"AETies")

lbl = Label(mw1
, text="you clicked the hidden message button")
lbl.pack()

mw1.mainloop()

mw = Tk()
mw.geometry(
"500x50+50+50")
mw.title(
"AETies : Automation Expert Technologies")

label = Label(mw
, text='Please click on button to close window')
label.pack(
side=LEFT)
btn = Button(mw
, text='hidden message', command=display_message)
btn.pack(
side=LEFT)

mw.mainloop()






Comments

My photo
Techno Xpresss
Bangalore, Karnataka, India