Python Tkinter同步画布图像加载

uz75evzq  于 2022-11-19  发布在  Python
关注(0)|答案(1)|浏览(170)

我有以下脚本创建2个窗口(MainImage)。主窗口包含一个名为Write的按钮,图像窗口包含一个没有图像的画布。当点击write按钮时,它会移动一个连接到我的树莓派的“马达”,然后更新画布上的图像。这个过程重复两次。不幸的是事实并非如此,在画布上刷新图像之前,马达移动了两次,我如何让它同步工作呢?

import tkinter as tk                    
from tkinter import *
from PIL import Image, ImageTk

# root window
root = tk.Tk()
root.geometry("500x500")
root.title("Main window")

images = [ImageTk.PhotoImage(Image.open("1.png")),
            ImageTk.PhotoImage(Image.open("2.png"))]

def move_motor():
    motor.init()
    motor.SetMicroStep('hardward','fullstep')
    motor.TurnStep("forward", steps=50, stepdelay = 1000)
    motor.Stop()

ctr = 0
def update_image():
   global ctr
   ctr += 1
   print(f"Loading: {ctr} image")
   canvas.itemconfig(image_container, image = images[ctr])

# --Problematic function-- #
def write_operations():
    for i in range(1, 3):
        move_motor() # operation 1
        update_image() # operation 2

# image window containing a canvas
imageWin = Toplevel(root)
imageWin.title("Image window")
imageWin.geometry("768x768")
canvas = Canvas(imageWin, width=768, height=768)
image_container = canvas.create_image(0, 0, anchor = NW, image = None)
canvas.pack()

btn_write = Button(root, text ="Write", command = write_operations).place(x = 130, y = 280)

root.mainloop()
erhoui1w

erhoui1w1#

我模拟了你的程序,在发动机点火上放了一个轻微的延迟。我用after替换了for循环,如果after延迟大于sleep时间,一切都正常。

import time
from tkinter import *

# root window
root = tk.Tk()
root.geometry("500x500")
root.title("Main window")

def move_motor():
    time.sleep(0.5)

ctr = 0
txt = None

def update_image(fr):
    global ctr, txt
    ctr += 1
    print(f"Loading: {ctr} image")
    if txt:
        canvas.delete(txt)
    txt = canvas.create_text(100, 100, text=ctr, justify=CENTER, font="Verdana 34")
    if ctr == 2:
        root.after_cancel(fr)
        ctr = 0

def write_operations():
    fr = root.after(1000, write_operations)
    move_motor()  # operation 1
    update_image(fr)  # operation 2


# image window containing a canvas
imageWin = Toplevel(root)
imageWin.title("Image window")
imageWin.geometry("768x768")
canvas = Canvas(imageWin, width=768, height=768)
image_container = canvas.create_image(0, 0, anchor=NW, image=None)
canvas.pack()

btn_write = Button(root, text="Write", command=write_operations).place(x=130, y=280)

root.mainloop()

相关问题