Python 如何将回车键绑定到 tkinter 中的函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16996432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I bind the enter key to a function in tkinter?
提问by Ghosty
I am a Python beginning self-learner, running on MacOS.
我是一名 Python 初学者,在 MacOS 上运行。
I'm making a program with a text parser GUI in tkinter, where you type a command in a Entrywidget, and hit a Buttonwidget, which triggers my parse()funct, ect, printing the results to a Textwidget, text-adventure style.
我正在使用 tkinter 中的文本解析器 GUI 制作一个程序,您可以在其中在Entry小部件中键入一个命令,然后点击一个Button小部件,这会触发我的parse()功能,等等,将结果打印到Text小部件,文本冒险风格。
> Circumvent the button
I can't let you do that, Dave.
> 绕过按钮
我不能让你那样做,戴夫。
I'm trying to find a way to get rid of the need to haul the mouse over to the Buttonevery time the user issues a command, but this turned out harder than I thought.
我试图找到一种方法来摆脱Button每次用户发出命令时都需要将鼠标拖到鼠标上的需要,但这比我想象的要难。
I'm guessing the correct code looks like self.bind('<Return>', self.parse())? But I don't even know where to put it. root, __init__, parse(), and create_widgets()don't want it.
我猜正确的代码看起来像self.bind('<Return>', self.parse())?但我什至不知道把它放在哪里。root, __init__, parse(), 和create_widgets()不想要它。
To be clear, the only reason anyone should hit enter in the prog is to trigger parse(), so it doesn't need to be espoused to the Entrywidget specifically. Anywhere it works is fine.
需要明确的是,任何人都应该在 prog 中点击 enter 的唯一原因是 trigger parse(),因此不需要Entry专门支持小部件。它在任何地方都很好。
In response to 7stud, the basic format:
响应7stud,基本格式:
from tkinter import *
import tkinter.font, random, re
class Application(Frame):
def __init__(self, master):
Frame.__init__(self, master, ...)
self.grid()
self.create_widgets()
self.start()
def parse(self):
...
def create_widgets(self):
...
self.submit = Button(self, text= "Submit Command.", command= self.parse, ...)
self.submit.grid(...)
root = Tk()
root.bind('<Return>', self.parse)
app = Application(root)
root.mainloop()
采纳答案by 7stud
Try running the following program. You just have to be sure your window has the focus when you hit Return--to ensure that it does, first click the button a couple of times until you see some output, then without clicking anywhere else hit Return.
尝试运行以下程序。你只需要确保你的窗口在你点击 Return 时有焦点——为了确保它有焦点,首先点击按钮几次直到你看到一些输出,然后不要点击其他任何地方点击 Return。
import tkinter as tk
root = tk.Tk()
root.geometry("300x200")
def func(event):
print("You hit return.")
root.bind('<Return>', func)
def onclick():
print("You clicked the button")
button = tk.Button(root, text="click me", command=onclick)
button.pack()
root.mainloop()
Then you just have tweak things a little when making both the button clickand hitting Returncall the same function--because the command function needs to be a function that takes no arguments, whereas the bind function needs to be a function that takes one argument(the event object):
然后,在使 thebutton click和hitting Returncall 相同的函数时,您只需稍微调整一下——因为 command 函数需要是一个不带参数的函数,而 bind 函数需要是一个带一个参数的函数(事件对象):
import tkinter as tk
root = tk.Tk()
root.geometry("300x200")
def func(event):
print("You hit return.")
def onclick(event=None):
print("You clicked the button")
root.bind('<Return>', onclick)
button = tk.Button(root, text="click me", command=onclick)
button.pack()
root.mainloop()
Or, you can just forgo using the button's command argument and instead use bind() to attach the onclick function to the button, which means the function needs to take one argument--just like with Return:
或者,您可以放弃使用按钮的命令参数,而是使用 bind() 将 onclick 函数附加到按钮上,这意味着该函数需要采用一个参数——就像使用 Return 一样:
import tkinter as tk
root = tk.Tk()
root.geometry("300x200")
def func(event):
print("You hit return.")
def onclick(event):
print("You clicked the button")
root.bind('<Return>', onclick)
button = tk.Button(root, text="click me")
button.bind('<Button-1>', onclick)
button.pack()
root.mainloop()
Here it is in a class setting:
这是在类设置中:
import tkinter as tk
class Application(tk.Frame):
def __init__(self):
self.root = tk.Tk()
self.root.geometry("300x200")
tk.Frame.__init__(self, self.root)
self.create_widgets()
def create_widgets(self):
self.root.bind('<Return>', self.parse)
self.grid()
self.submit = tk.Button(self, text="Submit")
self.submit.bind('<Button-1>', self.parse)
self.submit.grid()
def parse(self, event):
print("You clicked?")
def start(self):
self.root.mainloop()
Application().start()
回答by Se?kin Sava???
Another alternative is to use a lambda:
另一种选择是使用 lambda:
ent.bind("<Return>", (lambda event: name_of_function()))
Full code:
完整代码:
from tkinter import *
from tkinter.messagebox import showinfo
def reply(name):
showinfo(title="Reply", message = "Hello %s!" % name)
top = Tk()
top.title("Echo")
top.iconbitmap("Iconshock-Folder-Gallery.ico")
Label(top, text="Enter your name:").pack(side=TOP)
ent = Entry(top)
ent.bind("<Return>", (lambda event: reply(ent.get())))
ent.pack(side=TOP)
btn = Button(top,text="Submit", command=(lambda: reply(ent.get())))
btn.pack(side=LEFT)
top.mainloop()
As you can see, creating a lambda function with an unused variable "event" solves the problem.
如您所见,创建一个带有未使用变量“事件”的 lambda 函数解决了这个问题。
回答by Leon Chang
I found one good thing about using bind is that you get to know the trigger event: something like: "You clicked with event = [ButtonPress event state=Mod1 num=1 x=43 y=20]" due to the code below:
我发现使用 bind 的一个好处是您可以了解触发事件:例如:“您单击事件 = [ButtonPress event state=Mod1 num=1 x=43 y=20]”,原因如下:
self.submit.bind('<Button-1>', self.parse)
def parse(self, trigger_event):
print("You clicked with event = {}".format(trigger_event))
Comparing the following two ways of coding a button click:
比较以下两种编码按钮点击的方法:
btn = Button(root, text="Click me to submit", command=(lambda: reply(ent.get())))
btn = Button(root, text="Click me to submit")
btn.bind('<Button-1>', (lambda event: reply(ent.get(), e=event)))
def reply(name, e = None):
messagebox.showinfo(title="Reply", message = "Hello {0}!\nevent = {1}".format(name, e))
The first one is using the command function which doesn't take an argument, so no event pass-in is possible. The second one is a bind function which can take an event pass-in and print something like "Hello Charles! event = [ButtonPress event state=Mod1 num=1 x=68 y=12]"
第一个是使用不带参数的命令函数,因此不可能传入事件。第二个是绑定函数,它可以接收事件传入并打印类似“Hello Charles!event = [ButtonPress event state=Mod1 num=1 x=68 y=12]”的内容
We can left click, middle click or right click a mouse which corresponds to the event number of 1, 2 and 3, respectively. Code:
我们可以左击、中击或右击鼠标,分别对应事件编号 1、2 和 3。代码:
btn = Button(root, text="Click me to submit")
buttonClicks = ["<Button-1>", "<Button-2>", "<Button-3>"]
for bc in buttonClicks:
btn.bind(bc, lambda e : print("Button clicked with event = {}".format(e.num)))
Output:
输出:
Button clicked with event = 1
Button clicked with event = 2
Button clicked with event = 3

