首页 > 其他 > 详细

tkinter界面卡死的解决办法

时间:2016-02-12 06:04:28      阅读:1689      评论:0      收藏:0      [点我收藏+]

 0、如果点击按钮,运行了一个比较耗时的操作,那么界面会卡死

import tkinter as tk
import time

def onclick(text, i):
   time.sleep(3)
   text.insert(tk.END, 按了第{}个按钮\n.format(i))

   
   
root = tk.Tk()

text = tk.Text(root)
text.pack()

tk.Button(root, text=按钮1, command=lambda :onclick(text,1)).pack()
tk.Button(root, text=按钮2, command=lambda :onclick(text,2)).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(3)

def movie(movies, text):
    for m in movies:
        text.insert(tk.END, "看电影:%s \t-- %s\n" %(m, time.ctime()))
        time.sleep(5)

    
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()

 

方式二、继承 threading.Thread 类

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(3)

def movie(movies, text):
    for m in movies:
        text.insert(tk.END, "看电影:%s \t-- %s\n" %(m, time.ctime()))
        time.sleep(5)

class MyThread(threading.Thread):
    def __init__(self, func, *args):
        super().__init__()
        
        self.func = func
        self.args = args
        
        self.setDaemon(True)
        self.start()    # 在这里开始
        
    def run(self):
        self.func(*self.args)
    

root = tk.Tk()

text = tk.Text(root)
text.pack()

tk.Button(root, text=音乐, command=lambda :MyThread(music, songs)).pack()
tk.Button(root, text=电影, command=lambda :MyThread(movie, movies, text)).pack()

root.mainloop()

 

tkinter界面卡死的解决办法

原文:http://www.cnblogs.com/hhh5460/p/5186819.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!