Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
670 views
in Technique[技术] by (71.8m points)

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...