이런, 당신의 문제의 코드는 매우 familiar ...
이미지 파일이 어떤 신비한 지정되지 않은 프로세스에 의해 업데이트 할 수있는 기능이 필요하다는 복잡 된 테스트 코드로 구성 해답을 오는 보인다. 이것은 주 프로세스와 독립적으로 이미지 파일을 주기적으로 덮어 쓰는 별도의 스레드를 만들어 아래 코드에서 수행됩니다. 나는 약간의 혼란을 느끼고 일들이 실제로보다 복잡해 보이기 때문에이 코드를 나머지 부분과 함께 설명하려고 시도했다.
주요 테이크 어웨이는 universal tkinter widget after()
메소드를 사용하여 나중에 이미지를 새로 고침하도록 예약해야한다는 것입니다. 장소 소유자 캔바스 이미지 객체를 처음 만들면 이후에 해당 위치에서 업데이트 할 수 있도록주의를 기울여야합니다. 다른 캔버스 객체가있을 수 있기 때문에 필요합니다. 그렇지 않으면 자리 표시자가 작성되지 않은 경우 상대 위치에 따라 업데이트 된 이미지를 덮을 수 있습니다 (이미지 객체 ID가 저장되어 나중에 변경되도록 사용됨). 그것).
from PIL import Image, ImageTk
import tkinter as tk
#------------------------------------------------------------------------------
# Code to simulate background process periodically updating the image file.
# Note:
# It's important that this code *not* interact directly with tkinter
# stuff in the main process since it doesn't support multi-threading.
import itertools
import os
import shutil
import threading
import time
def update_image_file(dst):
""" Overwrite (or create) destination file by copying successive image
files to the destination path. Runs indefinitely.
"""
TEST_IMAGES = 'test_image1.png', 'test_image2.png', 'test_image3.png'
for src in itertools.cycle(TEST_IMAGES):
shutil.copy(src, dst)
time.sleep(.5) # pause between updates
#------------------------------------------------------------------------------
def refresh_image(canvas, img, image_path, image_id):
try:
pil_img = Image.open(image_path).resize((400,400), Image.ANTIALIAS)
img = ImageTk.PhotoImage(pil_img)
canvas.itemconfigure(image_id, image=img)
except IOError: # missing or corrupt image file
img = None
# repeat every half sec
canvas.after(500, refresh_image, canvas, img, image_path, image_id)
root = tk.Tk()
image_path = 'test.png'
#------------------------------------------------------------------------------
# More code to simulate background process periodically updating the image file.
th = threading.Thread(target=update_image_file, args=(image_path,))
th.daemon = True # terminates whenever main thread does
th.start()
while not os.path.exists(image_path): # let it run until image file exists
time.sleep(.1)
#------------------------------------------------------------------------------
canvas = tk.Canvas(root, height=400, width=400)
img = None # initially only need a canvas image place-holder
image_id = canvas.create_image(200, 200, image=img)
canvas.pack()
refresh_image(canvas, img, image_path, image_id)
root.mainloop()
는 그냥 예를 제공하거나 좀 더 설명해 주시겠습니까 수있는 타이머 –
@PadraicCunningham에 콜백을 만들 수 있습니다. 나는 이것에 처음이에요. – lads
'root.after (500, your_function)', 함수를 추가하면 이미지가 추가됩니다. –