python - tkinter中的while循环太慢
问题描述
当我在 tkinter 中创建一个 while 循环时,它运行得太慢了。
这是代码:
from tkinter import *
import threading
root = Tk()
line = 1
col = 0
loop_count = 1
def highlight_one_by_one():
global col , loop_count
while True:
text.tag_add("highlight" , f"{line}.{col}" , f"{line}.{col + 1}")
text.tag_config("highlight" , foreground = "yellow" , background = "blue")
col += 1
loop_count += 1
if loop_count >= len(text.get(1.0 , END)):
print("done")
break
text = Text(root, width = 69 , height = 25 , font = "Consolas 14")
text.grid(row=0 , column = 0)
highlight_button = Button(root, text = "Highlight all letters one by one" , command = lambda: threading.Thread(target=highlight_one_by_one , daemon=True).start())
highlight_button.grid(row = 1 , column = 0 , pady = 5)
text.insert(END , "This is a text widget\t\t"*500)
mainloop()
在这里,我创建了一个程序,其中 tkinter 将一个一个地突出显示文本小部件中的所有字母。但问题是循环太慢了。突出显示文本小部件中的所有字母大约需要 30 秒。当我向文本小部件添加滚动条时,循环变得比以前更慢。我想要的是加速循环,以便这个循环可以在不到一秒的时间内突出显示所有字母。
我知道我可以使用text.tag_add("highlight" , 1.0 , END)
,但我没有这样做,因为在我的其他程序中,我编写了一些代码,其中只有特定的字母会被突出显示。
我在整个互联网上搜索了这个问题,但找不到任何解决方案。
有没有办法解决这个问题?
如果有人可以帮助我,那就太好了。
解决方案
我一直在试验,这工作得更快:
from tkinter import *
import threading
root = Tk()
line = 1
col = 0
loop_count = 1
def highlight_at_once():
end = len(text.get(1.0 , END))
col = 0
text.tag_add("highlight" , f"{line}.{col}" , f"{line}.{col + end}")
text.tag_config("highlight" , foreground = "yellow" , background = "blue")
def highlight_one_by_one():
global col , loop_count
end = len(text.get(1.0 , END))
while True:
text.tag_add("highlight" , f"{line}.{col}" , f"{line}.{col + 1}")
col += 1
loop_count += 1
if loop_count >= end:
print("done")
break
text.tag_config("highlight" , foreground = "yellow" , background = "blue")
text = Text(root, width = 69 , height = 25 , font = "Consolas 14")
text.grid(row=0 , column = 0)
highlight_button = Button(root, text = "Highlight all letters one by one" , command = lambda: threading.Thread(target=highlight_one_by_one , daemon=True).start())
#highlight_button = Button(root, text = "Highlight all letters one by one" , command = highlight_at_once)
highlight_button.grid(row = 1 , column = 0 , pady = 5)
text.insert(END , "This is a text widget\t\t"*500)
mainloop()
推荐阅读
- c++ - void函数不传递参数c ++
- performance - JMeter 在线程 geoup 中跳过第二个 Get HTTP 请求
- flutter - 定义主题时如何设置输入文本颜色?
- c# - How to Select Items in an Observable Collection with a property that matches a criteria
- python - python键盘如何使按键仅在聚焦时才可检测
- javascript - 如何使用 Javascript/jQuery 或 NPM 库验证 SQL 查询语法?
- php - 使 FEOF 更快返回 true 以避免explode()“未定义偏移”错误(PHP)
- python - Django - 使用 TextInput 表单查找 ForeignKey
- c++ - 为什么 const 在“参数类型的最外层”被忽略?
- selenium - 从 Postman(或类似工具)触发/运行 Selenium 脚本