gpt4 book ai didi

python - 等到用户停止在 Tkinter 中输入

转载 作者:太空宇宙 更新时间:2023-11-04 00:50:16 25 4
gpt4 key购买 nike

在我的程序中,我想在用户输入时更新我的​​图形用户界面。然而,出于资源原因,我只想在用户没有输入 x 毫秒的内容时才这样做。这是一个有效的示例,但我不太喜欢它,因为它需要两个附加功能并且有点冗长。

import tkinter as tk
import random

COLORS =["red", "orange", "yellow", "green", "blue", "violet"]

class Application(tk.Frame):

def __init__(self,master):
self.counter = 0
self.master = master
tk.Frame.__init__(self)
self.pack()

self.entry = tk.Entry(self)
self.entry.pack()
self.entry.bind('<Key>',lambda event: self.handle_wait(event))


def handle_wait(self,event):
self.counter += 1
counter = self.counter
self.after(1000,lambda: self.handle_wait2(counter) )


def handle_wait2(self,counter):
if self.counter == counter:
self.change_color()

def change_color(self):
random_color = random.choice(COLORS)
self.entry.config(background=random_color)

root = tk.Tk()
app = Application(root)
app.mainloop()

有更好的方法吗?

最佳答案

解决方案是使用 after 安排函数在用户停止输入后运行。然后,您需要做的就是在每次点击按钮时重新启 Action 业。

首先,创建一个变量来存储代表 future 函数调用的 id。您也可以丢弃 self.counter,因为它不需要。

def __init__(...):
...
self._after_id = None
...

接下来,删除绑定(bind)中的 lambda。这是毫无意义的,并且使代码比它需要的更复杂:

self.entry.bind('<Key>',self.handle_wait)

最后,将您的 handle_wait 函数更改为如下所示:

def handle_wait(self, event):
# cancel the old job
if self._after_id is not None:
self.after_cancel(self._after_id)

# create a new job
self.after(1000, self.change_color)

这是一个基于您的代码的完整示例:

import tkinter as tk
import random

COLORS =["red", "orange", "yellow", "green", "blue", "violet"]

class Application(tk.Frame):

def __init__(self,master):
self.master = master
tk.Frame.__init__(self)
self.pack()

self._after_id = None
self.entry = tk.Entry(self)
self.entry.pack()
self.entry.bind('<Key>',self.handle_wait)

def handle_wait(self,event):
# cancel the old job
if self._after_id is not None:
self.after_cancel(self._after_id)

# create a new job
self._after_id = self.after(1000, self.change_color)

def change_color(self):
random_color = random.choice(COLORS)
self.entry.config(background=random_color)

root = tk.Tk()
app = Application(root)
app.mainloop()

关于python - 等到用户停止在 Tkinter 中输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37432598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com