本文实例讲述了python开发之thread实现布朗运动的方法。分享给大家供大家参考,具体如下:
这里我将给大家介绍有关python中thread来实现布朗运动的一个例子
下面是运行效果:
代码部分:
# brownian motion — an example of a multi-threaded tkinter program.
from tkinter import *
import random
import threading
import time
import sys
#画布大小
width = 400
height = 300
sigma = 10
buzz = 2
radius = 2
lambda = 10
fill = ‘red’
stop = 0 # set when main loop exits
def particle(canvas):
r = radius
x = random.gauss(width/2.0, sigma)
y = random.gauss(height/2.0, sigma)
p = canvas.create_oval(x-r, y-r, x+r, y+r, fill=fill)
while not stop:
dx = random.gauss(0, buzz)
dy = random.gauss(0, buzz)
dt = random.expovariate(lambda)
try:
canvas.move(p, dx, dy)
except tclerror:
break
time.sleep(dt)
def main():
global stop
root = tk()
canvas = canvas(root, width=width, height=height)
canvas.pack(fill=’both’, expand=1)
#粒子数目
np = 30
if sys.argv[1:]:
np = int(sys.argv[1])
for i in range(np):
t = threading.thread(target=particle, args=(canvas,))
t.start()
try:
root.mainloop()
finally:
stop = 1
main()
希望本文所述对大家python程序设计有所帮助。