让Tkinter的after()按调用的时间顺序返回输出

2024-10-03 00:29:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个程序来记录一些测量结果。为了每秒记录一次,我在日志函数log()的末尾使用after()来调用它。这是在创建递归,因此不按时间顺序返回日志吗?(每秒打印超过1个日志)如何确保每个条目按时间顺序以每秒打印1个日志?你知道吗

以下是我的一些代码:

 def log(self):

    if self.running ==True:

        self.current_date = time.strftime("%Y-%m-%d")
        now = datetime.datetime.now()
        self.current_time = datetime.time(now.hour, now.minute, now.second)

        if self.boolvars[0].get() == True:
            self.t = self.t + str(self.current_date) + ", "
        if self.boolvars[1].get() == True:
            self.t = self.t  + str(self.current_time) + ", "
        if self.boolvars[2].get() == True:
            self.t = self.t + str(self.mic.VacGetPressure(0)) + ", "
            self.champres.append(str(self.mic.VacGetPressure(0)))
        if self.boolvars[3].get() == True:

       ...
       ...
       ...

        self.screen.insert(INSERT, self.t)
        self.parent.after(1000,self.log)

以下是一些示例输出:

2017-06-16, 13:18:37, 0.001,
2017-06-16, 13:18:36, 0.001,
2017-06-16, 13:18:36, 0.001,
2017-06-16, 13:18:36, 0.001,
2017-06-16, 13:18:37, 0.001,
2017-06-16, 13:18:37, 0.001,
2017-06-16, 13:18:37, 0.001,
2017-06-16, 13:18:36, 0.001,
2017-06-16, 13:18:36, 0.001,
2017-06-16, 13:18:36, 0.001,
2017-06-16, 13:18:37, 0.001,
2017-06-16, 13:18:37, 0.001,
2017-06-16, 13:18:37, 0.001,
2017-06-16, 13:18:38, 0.001,
2017-06-16, 13:18:36, 0.001,
2017-06-16, 13:18:36, 0.001,
2017-06-16, 13:18:36, 0.001,
2017-06-16, 13:18:37, 0.001,

在第二列中,很明显日志记录每秒发生不止一次,并且没有按时间顺序返回。 对after()的任何解释都会有帮助,如果我需要把它移出log(),或者放到哪里。你知道吗

提前谢谢。你知道吗


Tags: selflogtruegetdatetimeiftime顺序
2条回答

这个问题比我做的要简单得多(在完全研究我自己的代码之前,我学到了关于在溢出时发布到fast的经验)。我不是每次对log()的新调用都将self.t重置为空字符串。再次感谢你的回答。你知道吗

Is this creating a recursion and therefore not returning the logs in order of time?

不。对after来说更好的名字应该是add_job_to_queue。它不进行递归调用,只是向队列中添加一个函数。Tkinter将定期处理该队列,从中提取函数并调用它们。你知道吗

在调用self.log()一次之后,队列上只有一个项目。当tkinter处理队列时,它将弹出项目并运行它。在运行期间,会向队列中添加一个新作业。然后tkinter会把它从队列中弹出,然后添加一个新的。等等。队伍永远不会超过一个。你知道吗

您描述的行为听起来像是在启动多个调用self.log()的“循环”,和/或使用线程。你知道吗

相关问题 更多 >