如何将Enter键绑定到Tkinter按钮

Rah*_*hul 2 python bind tkinter button tkinter-entry

我试图将Enter键按钮绑定。

在下面的代码中,我试图从条目小部件中获取条目,当bt按下按钮时,它将调用enter()获取条目的方法。

我也希望通过按Enter键来调用它,但没有得到想要的结果。

在输入小部件中输入的值未读取,调用了enter方法,仅在我的数据库中插入了一个空格

帮我找出我的问题,谢谢!

from tkinter import *
import sqlite3

conx = sqlite3.connect("database_word.db")

def count_index():
    cur = conx.cursor()
    count = cur.execute("select count(word) from words;")
    rowcount = cur.fetchone()[0]
    return rowcount

def enter():  #The method that I am calling from the Button
    x=e1.get()
    y=e2.get()
    ci=count_index()+1
    conx.execute("insert into words(id, word, meaning) values(?,?,?);",(ci,x,y))
    conx.commit()

fr =Frame()  #Main
bt=Button(fr)  #Button declaration
fr.pack(expand=YES)
l1=Label(fr, text="Enter word").grid(row=1,column=1)
l2=Label(fr, text="Enter meaning").grid(row=2,column=1)
e1=Entry(fr)
e2=Entry(fr)
e1.grid(row=1,column=2)
e2.grid(row=2,column=2)
e1.focus()
e2.focus()
bt.config(text="ENTER",command=enter)
bt.grid(row=3,column=2)
bt.bind('<Return>',enter)   #Using bind

fr.mainloop()
Run Code Online (Sandbox Code Playgroud)

cbj*_*rup 8

在问题和小说的回答中,首先,按钮enter使用bt.config(text="ENTER",command=enter). 之后,功能绑定到回车键,但其实按钮和回车键还是相当独立的。

在这个问题的情况下,我假设这不是一个真正的问题,但是如果您经常想要更改按钮的命令,那么每次都必须更改与回车/返回键的绑定可能会很无聊。

所以你可能会想:有没有办法让回车键自动给出与按钮相同的命令?

就在这里!

Tkinter Button 有invoke()方法,它调用按钮的命令并返回命令的返回值:

import tkinter as TK

def func():
    print('the function is called!')

root = TK.Tk()
button= TK.Button(root, text='call the function', command=func) # not func()!
button.pack()
button.invoke() # output: 'the function is called!'
root.mainloop()
Run Code Online (Sandbox Code Playgroud)

我们可以简单地将此方法绑定到回车键:

root.bind('<Return>', button.invoke) # again without '()'!
Run Code Online (Sandbox Code Playgroud)

但是等等,这会产生与以前相同的问题:该button.invoke()方法不接受event来自绑定的参数,但我们不能(轻松)更改该方法。解决方案是使用 lambda:

root.bind('<Return>', lambda event=None: button.invoke()) # This time *with* '()'!!!
Run Code Online (Sandbox Code Playgroud)

为了完整起见,我将在下面举一个例子:

import tkinter as TK

root = TK.Tk()
button= TK.Button(root)
button.pack()

def func1():
    print('func1 is called!')
    button.config(text='call func2', command=func2)
def func2():
    print('func2 is called!')

button.config(text='call func1', command=func1)

root.bind('<Return>', lambda event=None: button.invoke())
root.mainloop()
Run Code Online (Sandbox Code Playgroud)

解释:

  • 当您第一次按下 Enter 或单击按钮时,“func1 被调用!” 将被打印。
  • 当您第二次按下 Enter 或单击按钮时,“func2 被调用!” 将被打印。回车键应该和按钮一样,虽然键的绑定没有改变。


Nov*_*vel 5

2件事:

您需要修改函数以接受bind传递的参数。(您不需要使用它,但是您需要接受它)。

def enter(event=None):
Run Code Online (Sandbox Code Playgroud)

并且您需要将函数而不是结果传递给bind方法。所以放下()

bt.bind('<Return>',enter)
Run Code Online (Sandbox Code Playgroud)

请注意,这绑定了Return to Button,因此,如果其他东西具有焦点,则将无法工作。您可能想将此绑定到Frame

fr.bind('<Return>',enter)
Run Code Online (Sandbox Code Playgroud)

如果您想要一种按下对焦按钮的方式,则空格键已经可以这样做。