multithread4.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. """
  2. 使用多线程的情况 - 耗时间的任务在独立的线程中执行
  3. Version: 0.1
  4. Author: 骆昊
  5. Date: 2018-03-20
  6. """
  7. import time
  8. import tkinter
  9. import tkinter.messagebox
  10. from threading import Thread
  11. def main():
  12. class DownloadTaskHandler(Thread):
  13. def run(self):
  14. # 模拟下载任务需要花费10秒钟时间
  15. time.sleep(10)
  16. tkinter.messagebox.showinfo('提示', '下载完成!')
  17. # 启用下载按钮
  18. button1.config(state=tkinter.NORMAL)
  19. def download():
  20. # 禁用下载按钮
  21. button1.config(state=tkinter.DISABLED)
  22. # 通过daemon参数将线程设置为守护线程(主程序退出就不再保留执行)
  23. DownloadTaskHandler(daemon=True).start()
  24. def show_about():
  25. tkinter.messagebox.showinfo('关于', '作者: 骆昊(v1.0)')
  26. top = tkinter.Tk()
  27. top.title('单线程')
  28. top.geometry('200x150')
  29. top.wm_attributes('-topmost', 1)
  30. panel = tkinter.Frame(top)
  31. button1 = tkinter.Button(panel, text='下载', command=download)
  32. button1.pack(side='left')
  33. button2 = tkinter.Button(panel, text='关于', command=show_about)
  34. button2.pack(side='right')
  35. panel.pack(side='bottom')
  36. tkinter.mainloop()
  37. if __name__ == '__main__':
  38. main()