我正在读取一个文件“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 中不起作用?
如何做到这一点?
最佳答案
在调用 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()
关于python - 从服务器读取消息并将其存储在文件中并在 Tkinter 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23602682/