我有以下脚本创建2个窗口(Main
,Image
)。主窗口包含一个名为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()
1条答案
按热度按时间erhoui1w1#
我模拟了你的程序,在发动机点火上放了一个轻微的延迟。我用
after
替换了for
循环,如果after
延迟大于sleep
时间,一切都正常。