【问题标题】:python tkinter: destroy() not working after using threading.Timer()python tkinter:使用threading.Timer()后destroy()不起作用
【发布时间】:2021-12-13 13:44:52
【问题描述】:

代码第 1 部分

from tkinter import *
from PIL import Image, ImageTk
import threading

c1 = "#262626"

root = Tk()
root.overrideredirect(True)
root.configure(bg=c1)

def destroy():
    global root
    root.destroy()

def pr():
    print("asd")
    destroy()

def animation():
    threading.Timer(0.01, pr).start()

animation()
root.mainloop()


destroy()命令生效后,窗口关闭,但程序继续运行,只能在任务管理器或CMD的帮助下禁用它,但没有任何错误。

代码第 2 部分


login = Tk()

img = Image.open(selfDir + "\\ok.png").resize((50, 50), Image.ANTIALIAS)
test = ImageTk.PhotoImage(img)
label1 = Label(login, image=test, bg=c1)
label1.image = test
label1.place(x=330, y=145, width=50, height=50)

login.mainloop()

如果我在第一个之后运行这部分,我会看到一个错误:

tkinter.TclError:无法调用“图像”命令:应用程序已被销毁

但是如果我只运行这部分,没有第一个,那么它可以工作,我可以在窗口中看到照片

所以问题来了。 我需要在 threading.Timer() 之后关闭窗口 然后我需要用图像打开窗口

【问题讨论】:

  • 第一个global root不需要,第二个,不要从其他线程调用tkinter方法,你可以用after方法调度函数。第三,在第 1 部分之后使用代码第 2 部分是什么意思?第 2 部分是在主循环之后运行还是什么?
  • 我的意思是,当我只运行第二部分时,它工作得很好,但是如果我在“root.mainloop()”之后运行第二部分,在 root.destroy 之后,我会看到错误(我的英语不是很好)||我刚刚尝试了“after(1000, pr)”,它成功了,非常感谢

标签: python tkinter


【解决方案1】:

我只需要写 root.after(10, pr) 代替 threading.Timer(0.01, pr).start()

特别感谢Matiiss

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 2012-11-30
    • 1970-01-01
    • 2018-07-01
    • 1970-01-01
    • 2020-10-06
    相关资源
    最近更新 更多