两种不同的循环在tkinter(python)同时运行

发布于 2025-02-10 10:30:00 字数 2381 浏览 1 评论 0原文

我已经与Python-Requests制作了一个简单的聊天系统。有两个不同的文件是发件人,另一个是接收器。这两个文件的主要概念是 1。发件人文件包含一个while循环,该循环总是以消息为输入。后 给出消息作为输入,它将消息发送到网站。 2。接收器文件还包含一个wire循环,每次都会从网站收到请求 5秒。 现在,我想使用TKINTER在同一窗口中运行这两个不同的作品。怎么做?提前致谢。

sender.py代码在这里

import configme as con
import requests
import datetime
from cryptography.fernet import Fernet

nam = con.my_name
cookies_dict = con.cookie
key = con.crypto_key
url = con.base_url + '/config.php'



def makeID():
return datetime.datetime.now().timestamp()

# encription staff
fernet = Fernet(key)


# member joining message
if nam.__len__() != 0:
requests.get(url+f"?iD={makeID()}&name=<<<>>>&msg={nam} join the room.", cookies=cookies_dict)


with requests.Session() as r:

while True: 
        msg = input("Enter your Messege: ")

        if msg == ".exit":
            # r.get(url+f"?iD={makeID()}&name=<<<>>>&msg={nam} has left the room.", cookies=cookies_dict)
            break
        else:
            encMessage = fernet.encrypt(msg.encode())   
            messenger = {'iD': makeID() ,'name': nam , 'msg': encMessage}
            if msg != "":
                r.get(url, params=messenger, cookies=cookies_dict)

接收器。

import configme as con
import requests
import json
from cryptography.fernet import Fernet
from time import sleep
from datetime import datetime
from pytz import timezone
import pytz

cookies_dict = con.cookie
ozone = con.my_timezone
key = con.crypto_key
time_format = con.date_time_format
url = con.base_url + '/log.json'
t = con.receive_time    


# encription staff
fernet = Fernet(key)


timezone = timezone(ozone)

def setTime(t):
stamptime = int(float(t))
GMT0 = pytz.utc.localize(datetime.utcfromtimestamp(stamptime))
return GMT0.astimezone(timezone).strftime(time_format)


j = 0
while True:
r = requests.get(url, cookies=cookies_dict).text
message = json.loads(r)
message_sz = len(message)

if message_sz == 0:
    print("Looks like there are no message")
    break

for msg in message[j:]:
    local_time = setTime(msg['id'])

    if msg['nam'] == '<<<>>>':
        print(f"{local_time} :: {msg['nam']} :: {msg['msg']}")
    else:   
        decMessage = fernet.decrypt(bytes(msg['msg'], "utf-8")).decode()
        print(f"{local_time} :: {msg['nam']} :: {decMessage}")  

j = message_sz
sleep(t)

I have made a simple chat system with python-requests. There are two different files one is the sender and another is the receiver. the main concept of these two files is
1. sender file contains a while loop which always takes the message as input. after
giving the message as input, it sends the message to a website.
2. receiver file also contains a while loop which gets requests from the website after every
5 seconds.
Now I want to run these two different works in the same window with Tkinter. how to do it? Thanks in advance.

Sender.py Code is here

import configme as con
import requests
import datetime
from cryptography.fernet import Fernet

nam = con.my_name
cookies_dict = con.cookie
key = con.crypto_key
url = con.base_url + '/config.php'



def makeID():
return datetime.datetime.now().timestamp()

# encription staff
fernet = Fernet(key)


# member joining message
if nam.__len__() != 0:
requests.get(url+f"?iD={makeID()}&name=<<<>>>&msg={nam} join the room.", cookies=cookies_dict)


with requests.Session() as r:

while True: 
        msg = input("Enter your Messege: ")

        if msg == ".exit":
            # r.get(url+f"?iD={makeID()}&name=<<<>>>&msg={nam} has left the room.", cookies=cookies_dict)
            break
        else:
            encMessage = fernet.encrypt(msg.encode())   
            messenger = {'iD': makeID() ,'name': nam , 'msg': encMessage}
            if msg != "":
                r.get(url, params=messenger, cookies=cookies_dict)

Receiver.py code here...

import configme as con
import requests
import json
from cryptography.fernet import Fernet
from time import sleep
from datetime import datetime
from pytz import timezone
import pytz

cookies_dict = con.cookie
ozone = con.my_timezone
key = con.crypto_key
time_format = con.date_time_format
url = con.base_url + '/log.json'
t = con.receive_time    


# encription staff
fernet = Fernet(key)


timezone = timezone(ozone)

def setTime(t):
stamptime = int(float(t))
GMT0 = pytz.utc.localize(datetime.utcfromtimestamp(stamptime))
return GMT0.astimezone(timezone).strftime(time_format)


j = 0
while True:
r = requests.get(url, cookies=cookies_dict).text
message = json.loads(r)
message_sz = len(message)

if message_sz == 0:
    print("Looks like there are no message")
    break

for msg in message[j:]:
    local_time = setTime(msg['id'])

    if msg['nam'] == '<<<>>>':
        print(f"{local_time} :: {msg['nam']} :: {msg['msg']}")
    else:   
        decMessage = fernet.decrypt(bytes(msg['msg'], "utf-8")).decode()
        print(f"{local_time} :: {msg['nam']} :: {decMessage}")  

j = message_sz
sleep(t)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

懵少女 2025-02-17 10:30:00

我不建议您使用此检查并转到网站方法,但是您可以同时进行循环进行线索。并且您可以在需要使用tk.update()时更新TK。
您可以从螺纹循环设置并在单个TK窗口中使用的VAR获取数据。

I would not suggest using this checking and going to website method, but you could thread the while loops to go at the same time. And you could update tk when you want using tk.update().
You could get Data from vars that the threaded loops are setting and use them in your single tk window.

黑寡妇 2025-02-17 10:30:00

使用多线程。或其他单独加载数据。

use multi threading .or else load data separately.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文