python tkinter how to bind key to a button

2020-01-29 08:41发布

问题:

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)

回答1:

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.



回答2:

Use bind_all like this:

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

You can find more info at the Python docs.



回答3:

You can use bind. I'm going to assume the indenting in your question is wrong and sharpen is an Application method.

class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        master.wm_title("Image examples")
        self.pack()
        self.createWidgets()
        self.bind("s", self.sharpen)

Pythonware has useful information about event handling.