尝试运行以下程序。 当你点击Return时你必须确保你的窗口具有焦点 - 为了确保它确实如此,首先单击按钮几次,直到你看到一些输出,然后没有点击任何其他点击返回。
import tkinter as tk
root = tk.Tk()
root.geometry("300x200")
def func(event):
print("You hit return.")
root.bind('', func)
def onclick():
print("You clicked the button")
button = tk.Button(root, text="click me", command=onclick)
button.pack()
root.mainloop()
然后你只需稍微调整一下button click和hitting Return调用相同的函数 - 因为命令函数需要是一个不带参数的函数,而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('', 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('', onclick)
button = tk.Button(root, text="click me")
button.bind('', 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('', self.parse)
self.grid()
self.submit = tk.Button(self, text="Submit")
self.submit.bind('', self.parse)
self.submit.grid()
def parse(self, event):
print("You clicked?")
def start(self):
self.root.mainloop()
Application().start()