我正在阅读一个文件" 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中不起作用吗?
怎么做?
答案 0 :(得分:1)
在调用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()