栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将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()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/574822.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号