Python Tkinter多线程功能 [英] Python Tkinter Multithreading functions
问题描述
我目前正在使用python的tkinter库来处理电子邮件发件人和接收程序. 我正在使用线程模块使程序每60秒刷新一次未读的电子邮件,而您仍然可以继续在程序中执行操作.
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.
仅在执行print("something")命令时,线程模块即可工作,我仍然可以继续在程序中进行操作.但是,当我使线程登录gmail并获取未读电子邮件计数时,整个程序将冻结并崩溃.
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.
在功能上犯了一个小错误. get_credentials()已删除.
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()
推荐答案
此代码实际上正确吗?
您在多线程中调用它:
time.sleep(3)
multi = threading.Thread(target=multithreading)
multi.start()
您基本上是在告诉每个线程3秒后创建其自身的副本...我认为您错过了线程的要点.您可能应该有一个(单个)线程在while循环中运行,该线程从 Queue .
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.
示例代码
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)
这篇关于Python Tkinter多线程功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!