2013-12-17 68 views
0

我使用tkinter生成二維形態發生圖。我覺得它非常慢。例如,這個腳本在我的8核Xeon上需要將近10秒鐘:tkinter非常慢 - 如何加速或使用不同的庫?

#!/usr/bin/env python3 

import random 
import tkinter as tk 

A = 3.419384662527591 
B = 2.0158889752347022 
C = 19.479697084985673 
D = 61.006212908774614 
F = 1.3449991745874286 
G = 1.9590223710983992 
H = 5.129501734860241 
WIDTH = 800 
HEIGHT = 600 


class Morphogenic(tk.Frame): 

    def __init__(self, root): 
     tk.Frame.__init__(self, root) 
     self.canvas = tk.Canvas(width=WIDTH, height=HEIGHT, borderwidth=1) 
     self.canvas.pack(side="top", fill="both", expand=True) 

    def rand(self): 
     A = 3 + random.random() * 10 
     B = 1 + random.random() * 5 
     C = 1 + random.random() * 20 
     D = 1 + random.random() * 200 
     F = 1 + random.random() * 2 
     G = 1 + random.random() * 20 
     H = 1 + random.random() * 20 

    def draw(self): 
     points = [0] * HEIGHT 
     points_space = [0] * HEIGHT 
     points_energy = [0] * HEIGHT 
     w = WIDTH 
     h = HEIGHT 
     min_x = 0 

     last_x = 0 
     last_y = 0 

     while min_x < w: 
      min_x = w 
      lrand = 0 

      for y in range(1, h): 
       points_space[y] = points_space[y] + \ 
        (points_space[y - 1] - points_space[y])/F 

      for y in range(0, h): 
       lrand = lrand + (random.random() - 0.5)/C 
       new_point = points[y] + points_space[y] + lrand 
       points_space[y] = (new_point - points[y]) + \ 
        points_energy[y]/G 
       points_space[y] = points_space[y] + (A - points_space[y])/D 
       points_energy[y] = points_energy[y]/H 

       if (points_space[y] < B): 
        points_energy[y] = points_space[y] - B 
        points_space[y] = B 

       points[y] = points[y] + points_space[y] 

       if (min_x > points[y]): 
        min_x = points[y] 

       self.canvas.create_line(last_x, last_y, points[y], y) 
       last_x = points[y] 
       last_y = y 


if __name__ == "__main__": 
    root = tk.Tk() 
    m = Morphogenic(root) 
    m.pack(fill="both", expand=True) 
    m.rand() 
    m.draw() 
    root.mainloop() 

tkinter對於這類工作來說太弱了嗎?我應該看看不同的2D庫嗎?

回答

0

您的代碼正在創建超過150,000行。這開始推動畫布小部件的性能。它可以非常輕鬆地處理數千個物品,甚至數以萬計的物品。 150,000件商品比它旨在處理的要多一點。

+0

有什麼替代方案? Cyrex提到了PYside,我對此並不熟悉。任何其他? –

1

我也使用Tk作爲應用程序。

這是一個使用XML文件自動生成GUI的應用程序,而TK實在太慢了。

我切換到PYside,並已非常高興。它並不像Tkinter那麼容易使用,但它的速度更快,並具有很多可能性