Bind or Command to get return and button to work

谁都会走 提交于 2019-12-02 06:34:31

问题


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:


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



来源:https://stackoverflow.com/questions/18724986/bind-or-command-to-get-return-and-button-to-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!