python开发之thread实现布朗运动的方法

yipeiwu_com6年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

Python3 XML 获取雅虎天气的实现方法

参考廖雪峰的Python教程,实现Linux Python3获取雅虎天气 #!/usr/bin/env python3 # coding: utf-8 import os from...

Python判断一个list中是否包含另一个list全部元素的方法分析

本文实例讲述了Python判断一个list中是否包含另一个list全部元素的方法。分享给大家供大家参考,具体如下: 你可以用for in循环+in来判断 #!/usr/bin/env...

浅谈python中的__init__、__new__和__call__方法

前言 本文主要给大家介绍关于python中__init__、__new__和__call__方法的相关内容,分享出来供大家参考学习,下面话不多说,来一起看看详细的介绍: 任何事物都有一个...

Python时间差中seconds和total_seconds的区别详解

如下所示: import datetime t1 = datetime.datetime.strptime("2017-9-06 10:30:00", "%Y-%m-%d %H:...

浅谈Python 中整型对象的存储问题

在 Python 整型对象所存储的位置是不同的, 有一些是一直存储在某个存储里面, 而其它的, 则在使用时开辟出空间. 说这句话的理由, 可以看看如下代码: a = 5 b = 5...