[英]Why does the time.sleep work even before the window (tkinter) opens?
为什么 time.sleep time.sleep()
在 tkinter 的tkinter
打开之前起作用?
代码:
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)
You asked that why is time.sleep time.sleep()
is called before the windows loads because you hopefully called the window.mainloop()
at the last of the code which loads the window and keep maintain the tkinter window
The time.sleep time.sleep()
function code executes before the window.mainloop()
function so it was stop the execution and sleeps before the window could load
一个不错的方法是在if
语句中调用time.sleep()
。
Tk 实例要求您运行它的主循环 function 以便控制主进程线程。
您的代码在主进程线程上调用 time.sleep(),这会阻止 GUI 执行任何操作。 如果您希望能够在等待时使用 GUI 执行操作(例如绘制 window、四处移动或绘制其他东西),那么您需要扩展 Tk 以让 UI 使用 self.after 处理回调()
这是一个简单的示例,说明如何扩展 Tk class 以实现您想要的。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.