Home > Enterprise >  tkinter file reading only once in loop but it needs to read unlimited
tkinter file reading only once in loop but it needs to read unlimited

Time:11-04

I am trying to make a script that reads constantly and updates it on a tkinter UI, with a simple button to refresh, but I can't seem to make it work. I have used the while True to loop to read the file but that doesn't work, it only reads once and then it probably ends with the root.mainloop() line. Any solutions for me?

from tkinter import *

root = Tk()

root.geometry("400x400")

while True:

   with open('door1.txt', 'r') as f:
           f_contents = f.read()
           f.close

           

   def something():
       global my_label
       my_label.config(text=f_contents)
       

   my_label = Label(root, text="this is my first text")
   my_label.pack(pady=10)

   my_buttton = Button(root, text="C",command=something)
   my_buttton.pack(pady=10)



   root.mainloop() 

CodePudding user response:

Remove the while loop,
place the reading part in the something function,
remove f.close() because that is what context manager does automatically when exiting it.
Don't use * when importing modules, import what you need or import module (where module is the module name you need to import).
You don't need to use global my_label, it is already a globally accessible name and you are not changing what the name refers to.
Also you may want to put the function outside of the GUI parts so that they are kept separate and the code is more readable.

from tkinter import Tk, Label, Button


def something():
    with open('door1.txt', 'r') as f:
        f_contents = f.read()
    my_label.config(text=f_contents)


root = Tk()
root.geometry("400x400")

my_label = Label(root, text="this is my first text")
my_label.pack(pady=10)

my_buttton = Button(root, text="C", command=something)
my_buttton.pack(pady=10)

root.mainloop() 

CodePudding user response:

#try this

from tkinter import *

root = Tk()

root.geometry("400x400")

#don't change e unless you want to stop the loop
e=1
while e==1:

   with open('door1.txt', 'r') as f:
           f_contents = f.read()
           f.close

       

   def something():
       global my_label
       my_label.config(text=f_contents)
   

   my_label = Label(root, text="this is my first text")
   my_label.pack(pady=10)

  my_buttton = Button(root, text="C",command=something)
  my_buttton.pack(pady=10)

oh btw you misspelled button

  • Related