我想访问 MyApp 类中定义的文本字段,以从 MyThread 类 def run(self) 中写入“步骤 2”:类似这样的东西:
self.text.insert(1.0,"第二步")
代码:
import threading
import time
from Tkinter import *
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
time.sleep(5)
#i want to access the text here
class MyApp(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.my_widgets()
def my_widgets(self):
self.grid()
self.my_button = Button(self, text="Start my function",
command=self.my_function)
self.my_button.grid(row=0, column=0)
self.text = Text(self, width = 60, height = 5, wrap = WORD)
self.text.grid(row = 10, column = 0, columnspan = 2, sticky = W)
def my_function(self):
self.text.insert(1.0,"Step one")
mt = MyThread()
mt.start()
root = Tk()
root.title("Client")
root.geometry("500x500")
app = MyApp(root)
root.mainloop()
我对线程不是很熟悉,所以任何帮助都将不胜感激
@abarnet 使用您的答案,我这样做了,但是 GUI 在等待连接时没有响应
from Tkinter import *
from mtTkinter import *
import socket
import sys
class Application(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.submit_button = Button(self, text='start', command = self.my_function)
self.submit_button.grid(row = 2, column = 0, sticky = W)
self.text = Text(self, width = 60, height = 5, wrap = WORD)
self.text.grid(row = 10, column = 0, columnspan = 2, sticky = W)
def my_function(self):
mt = MyThread()
mt.start()
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def start(self):
app.text.insert(6.0,'server started')
app.text.update_idletasks()
app.text.insert(6.0,'\n'+'waiting for client')
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.bind(('',1090))
self.s.listen(1)
self.sc, address = self.s.accept()
address = str(address)
self.instruction = Label(self, text = 'got connection from '+address)
self.instruction.grid(row=7, column = 0, columnspan = 2, sticky = W)
self.instruction.update_idletasks()
msg = self.sc.recv(1024)
s=msg.find('.')
g=msg[s:]
i=1
f = open('file_'+ str(i)+g,'wb') #open in binary
i=i+1
while (True):
l = self.sc.recv(1024)
while (l):
f.write(l)
f.flush()
l = self.sc.recv(1024)
f.close()
self.sc.close()
self.s.close()
root = Tk()
root.title("Server")
root.geometry("500x250")
app = Application(root)
root.mainloop()