【问题标题】:Why does the time.sleep work even before the window (tkinter) opens?为什么 time.sleep 甚至在窗口(tkinter)打开之前就可以工作?
【发布时间】:2020-12-15 17:39:20
【问题描述】:

为什么time.sleep() 会在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)

【问题讨论】:

  • 请不要添加垃圾字符来解决网站规则。
  • 这是因为time.sleep()在主块中,代码首先被执行。

标签: python tkinter time


【解决方案1】:

你问为什么time.sleep()在windows加载之前被调用 因为您希望在加载窗口并保持维护 tkinter 窗口的代码的最后调用 window.mainloop()

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

一个不错的方法是在if 语句中调用time.sleep()

【讨论】:

    【解决方案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()
    

    【讨论】:

      猜你喜欢
      • 2015-07-28
      • 2021-06-19
      • 1970-01-01
      • 2017-01-17
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多