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程序设计有所帮助。

相关文章

初步探究Python程序的执行原理

初步探究Python程序的执行原理

1. 过程概述 Python先把代码(.py文件)编译成字节码,交给字节码虚拟机,然后虚拟机一条一条执行字节码指令,从而完成程序的执行。 2. 字节码 字节码在Python虚拟机程序里对...

浅谈tensorflow中张量的提取值和赋值

浅谈tensorflow中张量的提取值和赋值

tf.gather和gather_nd从params中收集数值,tf.scatter_nd 和 tf.scatter_nd_update用updates更新某一张量。严格上说,tf.ga...

Numpy array数据的增、删、改、查实例

准备工作: 增、删、改、查的方法有很多很多种,这里只展示出常用的几种。 >>> import numpy as np >>> a = np.ar...

使用Python和Prometheus跟踪天气的使用方法

开源监控系统 Prometheus 集成了跟踪多种类型的时间序列数据,但如果没有集成你想要的数据,那么很容易构建一个。一个经常使用的例子使用云端提供商的自定义集成,它使用提供商的 API...

浅谈python3中input输入的使用

浅谈python3中input输入的使用

今天谈一下关于python中input的一些基本用法(写给新手入门之用,故只谈比较实用的部分)。 首先,我们可以看一下官方文档给我们的解释(在python的shell中输入命令即可):...