singlethread2.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. def download():
  11. # 模拟下载任务需要花费10秒钟时间
  12. time.sleep(10)
  13. tkinter.messagebox.showinfo('提示', '下载完成!')
  14. def show_about():
  15. tkinter.messagebox.showinfo('关于', '作者: 骆昊(v1.0)')
  16. def main():
  17. top = tkinter.Tk()
  18. top.title('单线程')
  19. top.geometry('200x150')
  20. top.wm_attributes('-topmost', True)
  21. panel = tkinter.Frame(top)
  22. button1 = tkinter.Button(panel, text='下载', command=download)
  23. button1.pack(side='left')
  24. button2 = tkinter.Button(panel, text='关于', command=show_about)
  25. button2.pack(side='right')
  26. panel.pack(side='bottom')
  27. tkinter.mainloop()
  28. if __name__ == '__main__':
  29. main()
  30. # 在不使用多线程的情况下 一旦点击下载按钮 由于该操作需要花费10秒中的时间
  31. # 整个主消息循环也会被阻塞10秒钟无法响应其他的事件
  32. # 事实上 对于没有因果关系的子任务 这种顺序执行的方式并不合理