![](/img/trans.png)
[英]Rapidly Displaying Images from Raspberry Pi Camera onto tkinter Canvas
[英]Rapidly Display Images With Tkinter
我正在尋找一種使用 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%,並且無論我為每張圖片顯示的時間有多短,速度都非常慢。 有沒有更快、更有效的方法來做到這一點?
如前所述,我建議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()
您不需要使用線程。 第二,除非您在單獨的線程中使用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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.