绑定或命令以获得返回和按钮工作

2022-01-23 00:00:00 python tkinter events command button

问题描述

我有一个关于 bind() 方法和 command 参数的简单问题.通常,在程序中,您可以单击与您正在执行的操作相关的按钮来执行某些操作,或者只需按返回键.在下面的代码中,我尝试做同样的事情并且它确实有效.我只是在问自己这行 bttn.bind('<Button-1>', search) 是否有点奇怪,因为它将按钮内的鼠标单击与函数相关联,而不是按下按钮本身.

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.

一开始我不想包括按回车键来执行输入,我写了 bttn = Button(wd, text='Search', bg='Light Green', command=search),但此时 search 函数不是事件驱动函数,也没有事件参数.

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.

只要我想包含按返回键来完成相同的工作,我(当然)必须用 (event) 编写函数,因此使用 bind() 方法也用于鼠标按钮.

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

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


解决方案

在按钮和绑定之间共享功能的正常方法是使事件参数可选,并且不依赖它.你可以这样做:

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)

如果您省略 command 并依赖于绑定事件,您将失去 Tkinter 提供的内置键盘可访问性(您可以按 Tab 键并按空格键单击它).

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

相关文章