New to programming and especially python and tKinter. How can I create a way to bind the key "s" to the button or the function sharpen
? Any help would be awesome.
from Tkinter import *
from PIL import Image, ImageTk, ImageFilter, ImageEnhance
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
master.wm_title("Image examples")
self.pack()
self.createWidgets()
def createWidgets(self):
self.img = Image.open("lineage.jpg")
self.photo1 = ImageTk.PhotoImage(self.img.convert("RGB"))
self.label1 = Label(self, image=self.photo1)
self.label1.grid(row=0, column=0, padx=5, pady=5, rowspan=10)
self.photo2 = ImageTk.PhotoImage(self.img.convert("RGB"))
self.label2 = Label(self, image=self.photo2)
self.label2.grid(row=0, column=1, padx=5, pady=5, rowspan=10)
button5 = Button(self, text="Sharpen", command=self.sharpen)
button5.grid(row=4, column= 2, sticky = N)
def sharpen(self):
img2 = self.img.filter(ImageFilter.SHARPEN)
self.photo2 = ImageTk.PhotoImage(img2)
self.label2 = Label(self, image=self.photo2)
self.label2.grid(row=0, column=1, padx=5, pady=5, rowspan=10)
To bind the <Enter> key with an event in Tkinter window, we can use bind('<Return>', callback) by specifying the key and the callback function as the arguments. Once we bind the key to an event, we can get full control over the events.
To remap a key, click any key on that keyboard to select it and then choose another key from the drop-down list. After you log off and restart Windows, the key changes take effect. You can also use KeyTweak to remap specialty keys, such as the Volume key, that may appear on some keyboards.
You'll need to make two changes:
Add
master.bind('s', self.sharpen)
to __init__
. (Binding to the Frame, self
, does not seem to work.)
When s is pressed, self.sharpen(event)
will be called. Since
Tkinter will be sending a Tkinter.Event
object, we must also change the call
signature to
def sharpen(self, event=None):
Thus, when the button is pressed, event
will be set to the default
value, None
, but when the s key is pressed, event
will be assigned to the Tkinter.Event
object.
Use bind_all
like this:
def sharpen(self, event):
master.bind_all('s', sharpen)
You can find more info at the Python docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With