用Tkin快速显示图像

2024-10-01 19:25:40 发布

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

我正在寻找一种有效的方法来快速地用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%的使用率,是相当缓慢的,无论我使多少时间,每个图片显示。有没有更快捷、更有效的方法?你知道吗


Tags: 方法代码图像imageimporttimetkinterroot
2条回答

您不需要使用线程。第二,除非在单独的线程中使用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()

如前所述,我建议使用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()

相关问题 更多 >

    热门问题