invoke(): Triggering events without Clicking the button


Tkinter Button invoke()


We can simulate the button click event by using invoke().

In the below example, we are changing the text on the Label l1 on Click event of the buttons. Based on the which button is clicked we will change the text written on the Label.

Tkinter invoke() to simulate click event of a button without actually clicking the same
import tkinter as tk # Python 3
my_w = tk.Tk()
my_w.geometry("420x200") # width and height of the window

b1=tk.Button(my_w,text='One',font=28,
    command=lambda :l1.config(text='Button One '))
b1.grid(row=0,column=0,padx=30,pady=10)
b2=tk.Button(my_w,text='Two',font=28,
    command=lambda :l1.config(text='Button Two'))
b2.grid(row=0,column=1,padx=10,pady=10)

#command=lambda :l1.config(text='Button Two')
#command=lambda :b1.invoke()
l1=tk.Label(my_w,text='No Click ',bg='yellow',
    width=13,font=('Times',26,'normal'))
l1.grid(row=1,column=0,padx=30,pady=10,columnspan=3)
#b2.invoke() # Click or Command of button 2 
my_w.mainloop()
Here the default text on the Label l1 will be displayed and the same will change on click of any button.
By adding the line b2.invoke() we can show the text of button b2 on Label l1 . This is the default behavior which without the click of Second button b2.
b2.invoke()
Tkinter Button invoke() default


We can change the command part of button two( b2) to call the button 1 click event.
import tkinter as tk # Python 3
my_w = tk.Tk()
my_w.geometry("420x200") 

b1=tk.Button(my_w,text='One',font=28,
    command=lambda :l1.config(text='Button One '))
b1.grid(row=0,column=0,padx=10,pady=10)
b2=tk.Button(my_w,text='Two',font=28,
     command=lambda :b1.invoke())
b2.grid(row=0,column=1,padx=10,pady=10)
#command=lambda :l1.config(text='Button Two')
#command=lambda :b1.invoke()
l1=tk.Label(my_w,text='No Click',bg='yellow',font=('Times',26,'normal'))
l1.grid(row=1,column=0,padx=2,pady=10,columnspan=3)
b2.invoke() # Click or Command of button 2 
my_w.mainloop()
If we change the command for the button to create the click event for itself then what will happen ?
b2=tk.Button(my_w,text='Two',font=28,
    command=lambda :b2.invoke())
This will create error like this

RecursionError: maximum recursion depth exceeded while calling a Python object
Buttons Dynamic Buttons handling
Images used over button to create ON / Off switch
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer