簡體   English   中英

為什么 time.sleep 甚至在 window (tkinter) 打開之前就可以工作?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM