为什么time.sleep和冻结整个Python程序? [英] Why time.sleep and after freeze whole Python program?

查看:134
本文介绍了为什么time.sleep和冻结整个Python程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我使用TKinter的python程序中,函数code04调用printIt04,该函数每次打印一次并等待0.2秒。但是当调用code04时,整个应用程序会冻结,然后所有文本都会被打印一次。我该如何解决?



我尝试过:



In my python program using TKinter, the function "code04" calls printIt04 and that function prints something each time and waits for 0.2 seconds. but when "code04" called, the whole app freezes and then all of the text will be printed once. How can I solve it?

What I have tried:

	def code04(self):
		w = len(self.Matrix[0])
		for x in range(0, 8):
			self.printIt04(w, x)

.
.
.
	def printIt04(self, w, x):
		if (w > 200):
			MStartCol = int(round( (w - 200)/2))
			MEndCol = 200 + MStartCol
			IStartCol = 0
			IEndCol = 200
		else:
			MStartCol = 0
			MEndCol = w
			IStartCol = int(round( (200 - w)/2))
			IEndCol = IStartCol + w
		r = int(round( (w - 200)/2))
		for col in range(MStartCol, MEndCol):
			for row in range(0, x+1):
				if self.Matrix[7-row][col] == 1:
					self.img.put ("#ff0000", ( IStartCol - MStartCol + col, 7-row))
				else:
					self.img.put ("#000000", ( IStartCol - MStartCol + col, 7-row))
		time.sleep(0.2)

推荐答案

它之所以这样做是因为你的所有代码都在启动线程上运行,也就是所谓的UI线程。你的代码正在占用线程,阻止它接收和处理线程获得的WM_PAINT消息。在您的代码返回并且线程返回空闲状态之前,这些绘制消息将排队。当你最终放弃控制时,所有排队的消息都会被处理,窗口会被重新绘制,显示最终结果。



你要么必须使用计时器来打勾通过你的循环或将所有工作移动到后台线程,释放UI线程来处理消息。
The reason it does this is because all of your code is running on the startup thread, otherwise known as the "UI thread". Your code is hogging the thread, stopping it from receiving and processing the WM_PAINT messages the thread is getting. Until your code returns and the thread goes back to idle, these paint messages will just queue up. When you finally give up control all the queued message get processed and the window gets repainted showing you the end result.

You either have to use a timer to "tick" through your loop or move all of the "work" to a background thread freeing up the UI thread to process the messages.


这篇关于为什么time.sleep和冻结整个Python程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆