gpt4 book ai didi

python - Tkinter 和线程

转载 作者:太空宇宙 更新时间:2023-11-04 03:45:19 24 4
gpt4 key购买 nike

我是 python 的新手,我编写了一个基于客户端服务器的程序。我的客户端使用 Tkinter 作为 GUI,当程序进入与服务器通信的功能并运行整个程序时,GUI 卡住。我基本上知道为什么会这样,但我不知道如何在我的特定程序中修复它。

from Tkinter import *
import re
import os
import socket
import os.path
import time

MAXSIZE=5000000000 # bigest file u can send

class Application(Frame):

gateway =socket.socket(socket.AF_INET, socket.SOCK_STREAM)

def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.creat_widgets()

def creat_widgets(self):

self.instruction1 = Label(self,text = "Enter IP Address:")
self.instruction1.grid(row = 0, column = 0, columnspan = 2, sticky = W)

self.ipEntry = Entry(self)
self.ipEntry.grid(row = 0, column = 1, sticky = W + E)

self.instruction2 = Label(self, text = "Enter PORT:")
self.instruction2.grid(row = 1, column = 0, columnspan = 2, sticky = W)

self.portEntry = Entry(self)
self.portEntry.grid(row = 1, column = 1, sticky = W + E)

self.instruction3 = Label(self,text = "Enter Path:")
self.instruction3.grid(row = 2, column = 0, columnspan = 2, sticky = W)

self.pathEntry = Entry(self)
self.pathEntry.grid(row = 2, column = 1, sticky = W + E)


self.send_button = Button(self, text = "Send File" ,command = self.send_data)
self.send_button.grid(row = 3, column = 0, sticky = W)


self.inbox = Text(self, width = 40, height = 5, wrap = WORD)
self.inbox.grid(row =5,column = 0 , columnspan= 3)

def send_data(self):
content = self.ipEntry.get()
if(re.match("^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$",content)):
self.ip = content
else:
self.ip = False
content = self.portEntry.get()
if(re.match("^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$",content)):
self.port = content
else:
self.port = False
content = self.pathEntry.get()
if os.path.exists(content):
self.path = content
else:
self.path = False

if (self.ip and self.port and self.path):
self.connect()
if os.path.getsize(self.path)<=MAXSIZE:
self.update_text("Sending File......")
self.sendFile()
else:
self.update_text("FILE IS TOO BIG (MAX SIZE IS 500MB)")
else:
self.update_text("Error with entrys")



def connect(self):
try:
self.gateway.connect((self.ip, int(self.port)))
except socket.error, msg:
message = 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
self.update_text(message)



def sendFile(self):#send the file in the path entered
self.update_text("Sending File......")
tail = os.path.split(self.path)#get the files name and extention and send it to server.
self.gateway.sendall(tail[1])
self.sendLen()
try:
with open(str(self.path), 'rb') as f:
data = f.read()
self.gateway.sendall(data)
except Exception, e:
print e
if self.chkProt(self.gateway.recv(10)):
self.update_text("DONE!")



def sendLen(self):#Function that handles the the sending of the length of the file.
flen=os.path.getsize(str(self.path))
self.gateway.sendall(str(flen))
while self.chkProt(self.gateway.recv(10))==False:#checks that the length has been sent and received properly and no problems occurred.
self.gateway.sendall(str(flen)) #resend file length if a problem occurred.


def chkProt(self,num):#received a protocol that the server sent and act accordingly.
if num=="101":
return True
if num=="102":
print "AN ERROR HAS OCCURED"
return False
elif num=="103":
return False



def update_text(self, Etext):
# self.inbox.delete(0.0, END)
self.inbox.insert(0.0, Etext)


root = Tk()
root.title("HCFF")
root.geometry("300x200")

app = Application(root)

root.mainloop()

最佳答案

为避免卡住界面,您可以在单独的线程中运行send_data 函数(使用threading 模块)。只需导入它并在 create_widgets 函数中更改一行:

import threading

...

def creat_widgets(self):
....
self.send_button = Button(self, text = "Send File", command = lambda: threading.Thread(target=self.send_data).start())

关于python - Tkinter 和线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24123344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com