在单独的线程上插入来自大文件的文本时,tkui挂起

2024-04-25 21:40:55 发布

您现在位置:Python中文网/ 问答频道 /正文

即使在单独的线程中运行,当一个大文件被加载到文本小部件时,我的UI也会挂起。这仅仅是因为应用程序负载过重,还是有什么方法可以在发生这种情况时保持UI的功能。我在不同的小部件中加载了几个文本文件,所以挂断时间比预期的要长。你知道吗

from tkinter import *
import threading

i = 'large/text/file/400,000+lines'
root = Tk()

txt = Text(root)
txt.grid()


def loadfile():
    with open(i, 'r') as f:
        a = f.readlines()
        txt.insert('end', ' '.join(a))
        #for line in a:
         #   txt.insert('end', line)

def threadstarter():
    startit = threading.Thread(target=loadfile())
    startit.start()

btn = Button(root, text= 'start', command=lambda: threadstarter())
btn.grid()

root.mainloop()

在多台资源丰富的机器上进行了测试。你知道吗


Tags: textimporttxtui部件deflineroot
2条回答

为了在带有位置/关键字参数的单独线程中调用loadfile,请使用^{} and ^{} arguments to ^{},如下所示:

def threadstarter():
    startit = threading.Thread(target=loadfile, args=(42,), kwargs={'a': 'foo'})
    startit.start()

。。。它将在线程中调用loadfile(42, a='foo')。你知道吗

Bryan说的是你需要启动这样一个线程:

from tkinter import *
import threading

i = 'large/text/file/400,000+lines'
root = Tk()

txt = Text(root)
txt.grid()

def loadfile():
    with open(i, 'r') as f:
        txt.insert('end', f.read())

def threadstarter():
    startit = threading.Thread(target=loadfile)
    startit.start()

btn = Button(root, text= 'start', command=threadstarter)
btn.grid()

root.mainloop()

相关问题 更多 >

    热门问题