python 回车新函数_python - 如何将回车键绑定到tkinter中的函数? - 堆栈内存溢出...

本文介绍了如何在Python的Tkinter GUI中将回车键绑定到函数,以便在用户按下回车键时触发事件。通过示例代码展示了如何在按钮点击或直接按回车时调用相同的功能。
摘要由CSDN通过智能技术生成

尝试运行以下程序。 当你点击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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值