从服务器读取消息并将其存储在文件中并在Tkin中显示

2024-04-20 07:27:49 发布

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

我正在读取一个文件“server.txt”,在这个文件中,我接收来自客户端的文本消息,并将它们显示在Tkinter窗口中。这是密码

from Tkinter import *
import tkMessageBox

root = Tk()
frame = Frame(root)
frame.pack()
root.geometry("500x500")
text_area = Text(frame)
text_area.pack(side=BOTTOM)

while(1):
  text_area.delete(1.0, END)   
  fo = open("server.txt", "r")
  str = fo.read(500000);
  text_area.insert(END,str+'\n')
  print "Read String is : ", str
  # Close opend file
  fo.close()
root.mainloop()

当我在命令行中打开它时,它在ubuntu中不工作

怎么做


Tags: 文件text文本importtxt客户端servertkinter
1条回答
网友
1楼 · 发布于 2024-04-20 07:27:49

在调用root.mainloop()之前,您将一直循环使用while函数,这意味着Tkinter窗口将永远不会弹出,但您的while语句中的print语句将被大量垃圾邮件发送

这是工作代码,使用after函数after

    from Tkinter import *

# This function will be run every N milliseconds
def get_text(root,val,name):
    # try to open the file and set the value of val to its contents 
    try:
        with open(name,"r") as f:
            val.set(f.read())
    except IOError as e:
        print e
    else:
        # schedule the function to be run again after 1000 milliseconds  
        root.after(1000,lambda:get_text(root,val,name))

root = Tk()
root.minsize(500,500)
eins = StringVar()
data1 = Label(root, textvariable=eins)
data1.config(font=('times', 12))
data1.pack()
get_text(root,eins,"server.txt")
root.mainloop()

相关问题 更多 >