Reputation: 146
I am quite new to this site and python in general so excuse my messy code. I am trying to make a sort of instant messenger in python with a Tkinter interface. My school has a network on which one can exchange files and edit other peoples files if saved in the right area with the right permissions.
I have most of it figured out, The programm can save to a text file and read it too, however, the text widget which contains the text does not update by itself any and all attempts to make it do so have failed miserably. Any help would be appreciated as i can't seem to figure it out.
from tkinter import *
master = Tk()
master.geometry("300x200")
e = Entry(master)
e.pack()
def callback():
f = open("htfl.txt","a")
f.write(e.get())
print (e.get())
b = Button(master, text="get", width=10, command=callback)
b.pack()
file = open("htfl.txt","r") #opens file
#print(file.read(1))
a = file.read()
b = file.read()
print(file.read())
T = Text(master, height=9, width=30)
T.insert(END,a)
T.pack()
def update():
T.insert(END,a)
T.after(1000, update)
T.after(1000, update)
mainloop()
Upvotes: 4
Views: 26277
Reputation: 11
T.update() (without any parameters) just after T.insert(...) is OK for me.
Upvotes: 1
Reputation: 385800
You have to re-read the file each time you want to update the widget. For example:
def update():
with open("htfl.txt","r") as f:
data = f.read()
T.delete("1.0", "end") # if you want to remove the old data
T.insert(END,data)
T.after(1000, update)
Upvotes: 5
Reputation: 882
Instead of using Text
, you should use Label
. With a function called StringVar
you can update the label's text. A label is a widget which can display text onto the tk window. To use the Label
command and StringVar
, you need to:
example = StringVar()
example.set(END, a)
examplelabel = Label(master, textvariable=example)
examplelabel.pack()
The command StringVar()
is just making the text changable e.g.
example = StringVar()
example.set("Hello")
def whenclicked():
example.set("Goodbye")
changebutton = Button(master, text="Change Label", command=whenclicked)
changebutton.pack()
examplelabel = Label(master, textvariable=example)
examplelabel.pack()
This would cause the label to change to goodbye when the button is clicked. Hope I could help :)
Upvotes: -1