如何将Enter键绑定到tkinter中的函数?


问题内容

我是在MacOS上运行的Python入门自学者。

我正在tkinter中使用文本解析器GUI编写程序,在其中您可以在Entry窗口小部件中键入命令,然后单击Button窗口小部件,这将触发我的parse()功能,将结果打印为Text窗口小部件(文本冒险风格)。

绕开按钮

戴夫,我不能让你那样做。

我正在尝试寻找一种方法来摆脱Button每次用户发出命令时都要拖拉鼠标的麻烦,但是结果比我想象的要难。

我猜正确的代码是self.bind('<Return>', self.parse())什么样子?但是我什至不知道放在哪里。root__init__parse(),和create_widgets()不想要它。

需要明确的是,任何人都应该在prog中按回车键的唯一原因就是要触发parse(),因此不需要Entry专门支持该小部件。任何可行的地方都很好。

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

问题答案:

尝试运行以下程序。您只需要确保在单击“返回”时您的窗口具有焦点即可–要确保它具有此功能,请先多次单击按钮,直到看到一些输出,然后再单击“其他”,再单击“返回”。

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

然后,在同时使用button clickhitting Return调用相同的函数时,您只需稍作调整-
因为命令函数必须是不带参数的函数,而绑定函数需要是带一个参数的函数(事件对象):

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

或者,您可以放弃使用按钮的命令参数,而使用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()

这是在类设置中:

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