Tkinter在后台运行任务

时间:2019-03-06 23:29:27

标签: python python-3.x tkinter python-multithreading

我正在开发一个应用程序,您可以在其中向其他人发送消息(仅用于学习和测试目的),并且我希望打开一个窗口,让监听器在后台运行,等待有人在Google电子表格中输入内容(使用相同的程序输入电子表格并收听并显示该消息),我无法弄清楚该如何做(线程化?多处理?)。这是我的代码:

import gspread
from oauth2client.service_account import ServiceAccountCredentials
#basic import below
import os
import time
from time import gmtime, strftime
import sys
from queue import Queue
import getpass
import threading
from tkinter import *
import threading
#setup stuff

version = '1.0'
written = '3/5/2019'

currentUser = getpass.getuser()
print("Currrent User = " + currentUser)
jsonDict = {
  "type": "service_account",
  "project_id": "glossy-aloe-233621",
  "private_key_id": "c9f3e566e7482867e941bcd7129e2bbf87cf7429",
  "private_key": PRIVATEKEYSTUFF,
  "client_email": EMAIL STUFF,
  "client_id": "116858167893987826316",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/pymessengerclient%40glossy-aloe-233621.iam.gserviceaccount.com"
}


scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_dict(jsonDict, scope)
gc = gspread.authorize(credentials)
#get
wks = gc.open('PyMessenger').sheet1

#------------------------------------------------------------
#STUFF TO LOOK AT BELOW





def sendMessage(self, message):
  currentTime = strftime("%Y-%m-%d %H:%M:%S", gmtime())
  wks.append_row([str(currentUser), str(message), str(currentTime)])


def listener(self):
  i = 0
  lastM = ""
  while(True):
    colVals = wks.col_values(2)
    prevU = colVals[-1]
    if prevU != "Message":
      if lastM != prevU:
        cell = wks.find(prevU)
        row = cell.row
        vallist = wks.row_values(row)
        sent = vallist[0] + ": " + vallist[1] + " - " + vallist[2]
        print(vallist[0] + ": " + vallist[1] + " - " + vallist[2])
        txt.insert(0.0, sent)
        lastM = prevU
      else:
        pass
    time.sleep(2)



def createMessage(self):
  messageRaw = ent.get()
  self.sendMessage(messageRaw)

#---------------------------------------------
root = Tk()

root.geometry("400x300")
root.title("PyMessenger")

l1 = Label(root, text="Message:")

ent = Entry(root)

send = Button(root, text="Send", command=createMessage)

l1.grid(row=0, sticky=W)
ent.grid(row=1, column=0, sticky=W)

send.grid(row=2, column=0, sticky=W)

txt = Text(root, width=45, height=15, wrap=WORD)
txt.grid(row=3, columnspan=2, sticky=W)




#HERE RUN WINDOW & LISTEN TASK IN BACKGROUND
root.mainloop()

1 个答案:

答案 0 :(得分:0)

解决方案!

创建另一个函数(我称其为ThreadTask()),并将其放在a = threading.Thread(name='background', target=listener) a.start()中,并在“ root.mainloop()”之前的下面执行“ root.after(100,threadtask)”,然后将运行侦听器并通过将其放入另一个线程来停止冻结!