首页 > 解决方案 > 为什么我的 Python Tkinter GUI 运行缓慢并且没有响应?

问题描述

根据我通过阅读有关类似问题的其他 stackoverflow 主题的理解,由于 Python 是单线程的,我的 GUI 滞后。显然,我在我的代码中运行了两个 while 循环,但是,我无法确定它在我的代码中具体发生的原因。我知道我拥有的函数中有一个 for 循环,最后是 window.mainloop() 。

当我运行我的代码时,数字会在 GUI 中正确表示,但是,当拖动它或再次按下 START 按钮时,窗口本身会变得迟钝。所有这些最终都会破坏 GUI 并使其“无响应”。有关如何修复我的代码的任何建议,以便我可以在我的 GUI 中显示实时数据并让它在没有滞后的情况下工作?

from tkinter import *
import time
import statistics

dataList = []

def function():
    for i in range(10):

        dataList.append(i)

        time.sleep(1)

        currentLabel.configure(text="CURRENT")
        currentValue.configure(text=i)

        minLabel.configure(text="MIN")
        minValue.configure(text=min(dataList))

        maxLabel.configure(text="MAX")
        maxValue.configure(text=max(dataList))

        avgLabel.configure(text="AVG")
        avgValue.configure(text=round(statistics.mean(dataList)))

        window.update()

window = Tk()
window.title("Data Count")
window.geometry('800x750')
window.title("v1.0")

startBtn = Button(window, text="START", bg='#0388fc', fg='#ffffff', command=function)
startBtn.configure(font=("Ariel", 16))
startBtn.grid(column=1, row=5, pady=(25, 0))

currentLabel = Label(window)
currentLabel.grid(column=1, row=13)
currentValue = Label(window)
currentValue.grid(column=1, row=14)

avgLabel = Label(window)
avgLabel.grid(column=1, row=11)
avgValue = Label(window)
avgValue.grid(column=1, row=12)

minLabel = Label(window)
minLabel.grid(column=1, row=7)
minValue = Label(window)
minValue.grid(column=1, row=8)

maxLabel = Label(window)
maxLabel.grid(column=1, row=9)
maxValue = Label(window)
maxValue.grid(column=1, row=10)

window.mainloop()

标签: pythonpython-3.xmultithreadinguser-interfacetkinter

解决方案


推荐阅读