Tkinter在后台运行任务

2024-09-19 20:27:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个应用程序,你可以给其他人发信息(只是为了学习和测试的目的),我想打开一个窗口,让一个监听器在后台运行,等待有人在谷歌电子表格中键入一些内容(使用同一个程序输入电子表格,并监听和显示该信息),但我不能弄清楚怎么做(线程?多重处理。这是我的密码:

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

Tags: fromhttpsimportselfcomauthserviceroot
1条回答
网友
1楼 · 发布于 2024-09-19 20:27:53

解决方案!

创建另一个函数(我称之为ThreadTask())并将a = threading.Thread(name='background', target=listener) a.start()放入根.mainloop()'做'根.after(100,threadtask)“,这将运行侦听器并通过将其放入另一个线程来停止冻结!你知道吗

相关问题 更多 >