【问题标题】:Tkinter reading a file only once in loop when it needs to fo it infinitely many times当需要无限次执行时,Tkinter 仅在循环中读取文件一次
【发布时间】:2021-12-18 04:40:11
【问题描述】:

我正在尝试制作一个不断读取并在Tkinter GUI 上更新它的脚本,并使用一个简单的按钮进行刷新,但我似乎无法使其工作。 我已经使用while True 循环读取文件,但这不起作用,它只读取一次,然后它可能以root.mainloop() 行结束。有什么解决办法吗?

到目前为止我写的代码:

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() 

【问题讨论】:

    标签: python file tkinter


    【解决方案1】:

    删除 while 循环,
    将阅读部分放在something函数中,
    删除 f.close(),因为这是上下文管理器在退出时自动执行的操作。
    导入模块时不要使用*,导入你需要的或者import module(其中module是你需要导入的模块名称)。
    您不需要使用global my_label,它已经是一个可全局访问的名称,您无需更改名称所指的内容。
    此外,您可能希望将函数放在 GUI 部分之外,以便它们保持独立并且代码更具可读性。

    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() 
    

    【讨论】:

      猜你喜欢
      • 2011-07-29
      • 1970-01-01
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多