最近在打包运行时发现在进行复杂运算时会出现无响应问题,经过查找知道了tkinter是在主线程上运行,如果有复杂运算会堵塞主线程,遇见这种情况我们可以用多线程来解决。
下面的代码运行就会出现无响应情况,等延迟结束后,程序会恢复正常。
import tkinter as tk
import time
import threading
songs = ['爱情买卖', '朋友', '回家过年', '好日子']
movies = ['阿凡达', '猩球崛起']
def music(songs):
global text # 故意的,注意与movie的区别
for s in songs:
text.insert(tk.END, "听歌曲:%s \t-- %s\n" % (s, time.ctime()))
time.sleep(1)
def movie(movies, text):
for m in movies:
text.insert(tk.END, "看电影:%s \t-- %s\n" % (m, time.ctime()))
time.sleep(2)
root = tk.Tk()
text = tk.Text(root)
text.pack()
tk.Button(root, text='音乐', command=music(songs)).pack()
tk.Button(root, text='电影', command=movie(movies, text)).pack()
root.mainloop()
下面是加入多线程后的代码
import tkinter as tk
import time
import threading
songs = ['爱情买卖', '朋友', '回家过年', '好日子']
movies = ['阿凡达', '猩球崛起']
def music(songs):
global text # 故意的,注意与movie的区别
for s in songs:
text.insert(tk.END, "听歌曲:%s \t-- %s\n" % (s, time.ctime()))
time.sleep(1)
def movie(movies, text):
for m in movies:
text.insert(tk.END, "看电影:%s \t-- %s\n" % (m, time.ctime()))
time.sleep(2)
def thread_it(func, *args):
'''将函数打包进线程'''
# 创建
t = threading.Thread(target=func, args=args)
# 守护 !!!
t.setDaemon(True)
# 启动
t.start()
# 阻塞--卡死界面!
# t.join()
root = tk.Tk()
text = tk.Text(root)
text.pack()
tk.Button(root, text='音乐', command=lambda: thread_it(music, songs)).pack()
tk.Button(root, text='电影', command=lambda: thread_it(movie, movies, text)).pack()
root.mainloop()