繁体   English   中英

如何在使用python 3.6的回调过程中暂停?

[英]How to pause during a callback using python 3.6?

我是python的新手,正在为Othello编程计算机播放器。 我正在使用回调方法来查找鼠标单击板上的位置。 我需要能够在回调过程中暂停一下,以便先显示玩家的移动,再显示计算机的移动。 但是,目前,这两个动作同时发生,因此玩家看不到他/她的动作的结果。 当我尝试time.sleep()方法时,它只是延迟了整个回调的执行。 这是我的代码的简化版本:

from tkinter import *
import time
root = Tk()
root.configure(background="black")
canvas=Canvas(root, bg = "black", height = 708, width = 1280)
def callback(event):
    if event.y < 350:
        canvas.create_rectangle(500,234,780,334,fill="#004800",width=0)
        time.sleep(2)
        canvas.create_rectangle(500,374,780,474,fill="#004800",width=0)
    else:
        canvas.create_rectangle(500,374,780,474,fill="#004800",width=0)
        time.sleep(2)
        canvas.create_rectangle(500,234,780,334,fill="#004800",width=0)

canvas.bind("<Button-1>", callback)
canvas.pack(fill=BOTH, expand=1, pady=0, padx=0)      
root.mainloop()

这两个动作似乎同时发生,因为画布内容仅在time.sleep完成后才更新。 要单独查看第一步,您需要使用root.update_idletasks()强制画布在暂停之前进行更新。

顺便说一下,您不必导入模块time即可暂停,而可以使用root.after(2000) (时间以毫秒为单位)。

from tkinter import *
root = Tk()
root.configure(background="black")
canvas = Canvas(root, bg = "black", height = 708, width = 1280)

def callback(event):
    if event.y < 350:
        canvas.create_rectangle(500,234,780,334,fill="red",width=0)
        root.update_idletasks()
        root.after(2000)
        canvas.create_rectangle(500,374,780,474,fill="#004800",width=0)
    else:
        canvas.create_rectangle(500,374,780,474,fill="red",width=0)
        root.update_idletasks()
        root.after(2000)
        canvas.create_rectangle(500,234,780,334,fill="#004800",width=0)

canvas.bind("<Button-1>", callback)
canvas.pack(fill=BOTH, expand=1, pady=0, padx=0)      
root.mainloop()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM