Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python tkinter how to bind key to a button

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)
like image 273
iamtesla Avatar asked Nov 10 '12 23:11

iamtesla


People also ask

How do I bind the Enter key to a function in Tkinter?

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.

How do you bind a button?

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.


2 Answers

You'll need to make two changes:

  1. Add

    master.bind('s', self.sharpen)
    

    to __init__. (Binding to the Frame, self, does not seem to work.)

  2. 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.

like image 80
unutbu Avatar answered Oct 06 '22 01:10

unutbu


Use bind_all like this:

def sharpen(self, event):
    master.bind_all('s', sharpen)

You can find more info at the Python docs.

like image 40
Benjy Springall Avatar answered Oct 06 '22 00:10

Benjy Springall