使用Tkinter快速显示图像

时间:2019-01-04 13:53:19

标签: python image performance tkinter cpu-usage

我正在寻找一种有效的方法来使用tkinter 快速显示图像,我的意思是速度很快。目前,我有以下代码:

from tkinter import*
import threading
import time

root = Tk()
root.geometry("200x200")
root.title("testing")


def img1():
    threading.Timer(0.2, img1).start()
    whitei = PhotoImage(file="white.gif")
    white = Label(root, image=whitei)
    white.image = whitei
    white.place(x=0, y=0)

def img2():
    threading.Timer(0.2, img2).start()
    blacki = PhotoImage(file="black.gif")
    black = Label(root, image=blacki)
    black.image = blacki
    black.place(x=0, y=0)

img1()
time.sleep(0.1)
img2()

root.mainloop()

从本质上讲,该代码仅显示黑白图像,但是它使我的CPU处于100%的使用率,并且无论我花多长时间显示每张图片,它的速度都很慢。有更快,更有效的方法来做到这一点吗?

2 个答案:

答案 0 :(得分:1)

如前所述,我建议使用after。您实际上不应该在主线程之外更改任何tkinter对象。同样,每次创建一个新对象也不是最有效的。我可以尝试以下方法:

import tkinter as tk

root = tk.Tk()
root.geometry("200x200")
root.title("testing")

whitei = tk.PhotoImage(file="white_.gif")
blacki = tk.PhotoImage(file="black_.gif")

label = tk.Label(root, image=whitei)
label.image1 = whitei
label.image2 = blacki
label.place(x=0, y=0)

time_interval = 50

def img1():
    root.after(time_interval, img2)
    label.configure(image=whitei)

def img2():
    root.after(time_interval, img1)
    label.configure(image=blacki)

root.after(time_interval, img1)

root.mainloop()

答案 1 :(得分:1)

您不需要使用线程。第二,除非您在单独的线程中使用sleep(),否则切勿在tkinter应用程序中使用sleep。 sleep()会中断主循环,并会导致tkinter冻结直到睡眠完成。这是99.9%的时间,不是您想要的时间,因此在这里,您应将after()用于任何定时事件。

您可以为每个图像简单地创建每个标签,然后使用跟踪变量将正确的标签提升到顶部。

这是一个简单的例子。

from tkinter import *


root = Tk()
root.geometry("200x200")
root.title("testing")
current_image = ""

black_image = PhotoImage(file="black.gif")
white_image = PhotoImage(file="white.gif")
black_label = Label(root, image=black_image)
white_label = Label(root, image=white_image)
black_label.image = black_image
white_label.image = white_image
black_label.grid(row=0, column=0)
white_label.grid(row=0, column=0)


def loop_images():
    global current_image, black_image, white_image
    if current_image == "white":
        black_label.tkraise(white_label)
        current_image = "black"
    else:
        white_label.tkraise(black_label)
        current_image = "white"
    root.after(100, loop_images)

loop_images()
root.mainloop()