代码之家  ›  专栏  ›  技术社区  ›  Daniac

在Tkinter中正确使用after()

  •  0
  • Daniac  · 技术社区  · 8 年前

    我试图做的是运行另一个文件(file1进程),当该文件运行时,我想检查本地目录中是否存在文件。如果文件不存在,则所有内容都将继续运行,并在30秒内再次检查。如果文件确实存在,我想将内容打印到标签并停止file1进程。

    下面的代码会导致Tkinter擦除所有标签,并在发生延迟后冻结GUI。我哪里做错了?

    def turnOn():
      global proc
      if proc is None:
        window.after(5000,file_chk) 
        print('Starting Beacon')
        proc = subprocess.Popen(["python3", "/home/pi/FLBeacon/FLBeaconout.py"])
        label1 = Label(window,text ="Beacon is Running")
        label1.configure(bg='green')
        label1.place(x= 350, y=10, width=150)
        global  label2
        label2 = Label(window,text = full_message)
        label2.configure(bg='green')
        label2.place(x=50, y=90, width=550)
    
    def file_chk():    
        filelist = ['FLBeaconRecieved.txt']
        while True:
            list1 = []
            for file in filelist:
                list1.append(os.path.isfile(file))
    
            if all(list1):
               #all elements are true
               file = open("FLBeaconRecieved.txt")
               data = file.read()
               file.close()
               Results = Label(window, text = data)
               Results.place(x = 50, y = 350)
               print('Beacon Stopped')
               proc.terminate()
               proc = None
               label1 = Label(window,text = "Beacon is not running")
               label1.configure(bg='red')
               label1.place(x= 350, y=10, width=150)
               label2.destroy()
               break
            else:
              #time.sleep(30)
              print("there is no file")
    
    
    
    
    on = Button(window, borderwidth=2, text = "Start Beacon", width=15, pady=5, command = turnOn)
    off = Button(window, borderwidth=2, text = "Stop Beacon", width=15, pady=5, command = turnOff)
    on.place(x=215,y=300)
     off.place(x=380,y=300)
    
    
    def stop():
       window.destroy()
       #Top.destroy()
    
    b = Button(window, borderwidth=2, text="Update Beacon", width=15, pady=5, command=enter)
    b.place(x=50,y=300)
    b = Button(window, borderwidth=2, text="Exit", width=12, pady=5, command = combine_funcs(turnOff, stop))
    b.place(x=250,y=550)
    
    window.mainloop()
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Blckknght    8 年前

    而不是在 file_chk 要重复检查所需的文件,请让功能只检查一次文件,如果文件尚未准备好,请重新安排时间:

    def file_chk():    
        # ... (note, there should be no "while True" loop any more)
    
        if all(list1):  # check the condition just once
            # ...
        else:
            window.after(30000, file_chk) # if it failed, reschedule yourself