为什么time.sleep在窗口(tkinter)打开之前就工作了?

2024-09-27 18:22:05 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么在tkinter窗口打开之前time.sleep()工作

代码:

import tkinter
import time
window = tkinter.Tk()
window.geometry("500x500")
window.title("Holst")


holst = tkinter.Canvas(window, width = 450, height = 450, bg = "white")
holst.place(x = 25, y = 25)

x = 30
y = 50
d = 30

circle = holst.create_oval(x, y, x+d, y+d, fill = "red")
time.sleep(2)
holst.move(circle, 50, 40)

Tags: 代码importtimetitletkintersleepwindowwidth
2条回答

Tk实例要求您运行它的mainloop函数,以便控制主进程线程

您的代码正在主进程线程上调用time.sleep(),这会阻止GUI执行任何操作。如果您希望能够在等待时使用GUI进行操作(例如绘制窗口、移动窗口或向其绘制其他内容),那么您需要扩展Tk,让UI使用self.after()处理回调

下面是一个简单的示例,说明如何扩展Tk类以实现所需的功能

import tkinter

class TkInstance(tkinter.Tk):
    def __init__(self):
        tkinter.Tk.__init__(self)

        #Set up the UI here
        self.canvas = tkinter.Canvas(self, width = 450, height = 450, bg = "white")
        self.canvas.place(x = 25, y = 25) #Draw the canvas widget

        #Tell the UI to call the MoveCircle function after 2 seconds
        self.after(2000, self.MoveCircle) #in ms

    def MoveCircle(self):
        x = 30
        y = 50
        d = 30
        circle = self.canvas.create_oval(x, y, x+d, y+d, fill = "red")
        self.canvas.move(circle, 50, 40) #Draw the circle

#Main entrance point
if __name__ == "__main__": #good practice with tkinter to check this
    instance = TkInstance()
    instance.mainloop()

您询问了为什么在加载windows之前调用istime.sleep() 因为您希望在加载窗口并保持tkinter窗口的代码的最后一段调用window.mainloop()

time.sleep()函数代码在window.mainloop()函数之前执行,因此在加载窗口之前停止执行并休眠

一种很好的方法是在if语句中调用time.sleep()

相关问题 更多 >

    热门问题