Anupam Yadav Anupam Yadav -3 years ago 116
Python Question

Event binding with widget in tkinter in python

I have written a sample code in python 2.7. I have created a button and i want to associate this button with "F2" key of keyboard also i want that if i click on button "Click me", i want the same result. This code is not working fine. If anyone have idea, tell me.

from tkinter import *

root = Tk()

def callback(event):
print("hi")

b = Button(root, text="Click me")
b.pack()
b.bind("<F2>", callback)

root.mainloop()

Answer Source

This might work. I couldn't make your question exactly but this would solve the issue I presume.

from tkinter import *

root = Tk()

def callback(*args):
    print("hi")

root.bind("<F2>", callback)
b = Button(root, text="Click me") 
b.pack()
b.config(command = callback)
root.mainloop()

You need to bind the key to the function before or after you add the button to root.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download