Bind or Command to get return and button to work

2019-02-28 14:38发布

I have a simple question about the bind() method and the command argument. Usually, in a program, you can click on a button related to what you are doing to execute something or simply press the return key. In the code below, I tried to do the same and it does actually work. I was just asking myself if the line bttn.bind('<Button-1>', search) isn't a bit strange, as it relates the mouse click inside the button to the function, and not the pressing of the button itself.

At the beginning, I didn't want to include pressing the return key to execute the entry, and I had written bttn = Button(wd, text='Search', bg='Light Green', command=search), but at that point the search function wasn't an event driven function and had no event argument.

As soon as I wanted to include the return key pressing to do the same job, I had (of course) to write the function with (event), and thus use the bind() method for the mouse button as well.

Is this the "best way" to do it ? Or is there a more idiomatic way of doing it ?

Python3/Windows

from tkinter import *

def search(event):
    try:
        txtFile = open(str(entr.get()), 'r')
    except:
        entr.delete(0, END)
        entr.insert(0, "File can't be found")
    else:
        x = 0
        while 1:
            rd = txtFile.readline()
            if len(rd)> x:
                longest = rd
                x = len(rd)
            elif rd == '':
                break
        txtFile.close()
        entr.delete(0, END)
        entr.insert(0, longest)

#####MAIN#####

wd = Tk()
wd.title('Longest sentence searcher')
entr = Entry(wd, bg='White')
entr.grid(row=0, column=0)
entr.bind('<Return>', search)
bttn = Button(wd, text='Search', bg='Light Green')
bttn.grid(row=1, column =0)
bttn.bind('<Button-1>', search)

wd.mainloop()

1条回答
Fickle 薄情
2楼-- · 2019-02-28 15:00

The normal way to share a function between a button and a binding is to make the event parameter optional, and to not depend on it. You can do that like this:

def search(event=None):
    ...

bttn = Button(..., command=search)
...
entr.bind('<Return>', search)

If you omit the command and rely on a bound event, you lose the built-in keyboard accessibility that Tkinter offers (you can tab to the button and press the space bar to click it).

查看更多
登录 后发表回答