pythontk多线程,Python Tkinter多线程功能

I am currently working on an Email sender and recieving program with the tkinter library from python.

I am using the threading module to make the program refresh the unread emails every 60 seconds while you can still continue doing stuff in the program.

The threading module works when just making a print("something") command, and I can still continue doing stuff in the program. However, when I make the thread log into gmail and getting the unread email count, the whole program freezes and crashes.

Below is a snippet of my code. I will not post the full code, I made a short version to show how it looks.

EDIT:

Made a small fault in the function. the get_credentials() is removed.

import tkinter, re, threading, time, imaplib, too many to list here.

class Application(Frame):

def __init__(self, parent):

... Start some functions

... Create some widgets

... Create some global stringvars for entry fields

def threadrefresh(self):#I want to start this function when a button is clicked

def multithreading():

usernamevar = "Username"

passwordvar = "Password"

obj = imaplib.IMAP4_SSL('imap.gmail.com', '993') #connect to gmail

obj.login(usernamevar, passwordvar) #log in

obj.select() #select the inbox

unread = str(len(obj.search(None, 'UnSeen')[1][0].split())) #get the total unread

print(unread)

obj.close()

time.sleep(3)

multi = threading.Thread(target=multithreading)

multi.start()

multi = threading.Thread(target=multithreading)

multi.start()

def other_functions_that_do_not_matter_in_this_case():

... Creating GUI

... Sending mail

... Etc.

... Create a button with function call self.threadrefresh

def main():

root = Tk()

app = Application(root)

root.mainloop()

if __name__ == '__main__':

main()

解决方案

Is this code actually correct?

You call this in multithreading:

time.sleep(3)

multi = threading.Thread(target=multithreading)

multi.start()

You are basically telling every thread to create a copy of itself after 3 seconds... I think you are missing the point of a thread. You should probably have a (single) thread running in a while loop that gets data from a Queue.

Whenever you want the thread to act on something, you add it to the Queue.

Edit: Example code

import threading

import Queue

import time

def f(q):

while True:

print q.get() #block thread until something shows up

q = Queue.Queue()

t = threading.Thread(target=f,args=[q])

t.daemon = True #if parent dies, kill thread

t.start()

for x in range(0,1000):

q.put(x)

time.sleep(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值