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

如何将Enter键绑定到tkinter中的函数?,第1张

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

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

import tkinter as tkroot = 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 click
hitting Return
调用相同的函数时,您只需稍作调整-
因为命令函数必须是不带参数的函数,而绑定函数需要是带一个参数的函数(事件对象):

import tkinter as tkroot = 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 tkroot = 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 tkclass 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()


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5566062.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存