Python Tkinter Multithreading functions

2019-08-07 11:55发布

问题:

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

回答1:

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)