如何使用Tkinter来展示时间序列数据?

2024-07-03 06:30:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Tkinter来可视化一些时间序列数据。我的数据是二维矩阵的形式,行表示块,列表示某个时间段。所有值都在0和1之间。在

我想用Tkinter创建一个python脚本,它创建一个窗口,在一个正方形矩阵中显示块,第一列决定每个块的亮度,然后在预定的时间之后,根据数据中连续的列更改块的亮度。在

我已经创造了一个版本:

#!/usr/bin/python

import sys
import os.path
import Tkinter as tk
import math

# program constants
WINDOW_WIDTH = 900

# function to change the colours of the blocks based on current period
def redrawPeriod(t):
    for b in xrange(len(blocks)):
        luminance = int(blocks[b][t] * 255)
        colour = "#%x%x%x" % (luminance,luminance,luminance)
        canvas.itemconfig(block_ids[b],fill=colour)

# sample data (4 blocks 4 periods)
blocks = [
        [0.0, 0.2, 0.5, 0.8],
        [0.3, 0.0, 0.4, 0.0],
        [0.5, 0.7, 0.0, 1.0],
        [0.0, 0.0, 0.3, 0.6],
        [1.0, 0.5, 0.2, 0.9]
      ]

# get number of blocks and periods
nB = len(blocks)
nT = len(blocks[0])

n_cols = int(math.sqrt(nB))
n_rows = n_cols

# if not perfect square number of blocks, add extra row
if (nB % n_rows != 0):
    n_rows = n_rows + 1

# calculate block size
BLOCK_SIZE = WINDOW_WIDTH / n_cols
WINDOW_HEIGHT = BLOCK_SIZE * n_rows

# initialise Tkinter
root = tk.Tk()

# initialise canvas
canvas = tk.Canvas(root, width=WINDOW_WIDTH, height=WINDOW_HEIGHT, background="#002080")

# open canvas
canvas.pack()

# container for block objects
block_ids = []

x = 0
y = -1*BLOCK_SIZE

# initialise block objects
for b in xrange(nB):
    if (b % n_cols == 0):
        x = 0
        y = y + BLOCK_SIZE

    luminance = int(blocks[b][0] * 255)
    colour = "#%x%x%x" % (luminance,luminance,luminance)
    id = canvas.create_rectangle(x, y, x+BLOCK_SIZE, y+BLOCK_SIZE, outline="",fill = colour)
    block_ids.append(id)
    x = x + BLOCK_SIZE

for t in xrange(nT):
    root.after(1000, redrawPeriod,t)

root.mainloop()

这似乎是我想要它做的,但是它每次都直接跳转到最后一帧——也就是说,它不画一帧,不停,不画另一帧,再停,等等

谁能帮我弄清楚我做错了什么吗?在


Tags: importforsizetkinterrootwindowblockrows
1条回答
网友
1楼 · 发布于 2024-07-03 06:30:03

你的问题是当你打电话给:

for t in xrange(nT):
    root.after(1000, redrawPeriod,t)

root.after()不会阻止执行,因此for循环执行得非常快,并且所有重画事件都会在1000毫秒后同时调用

在Tkinter中运行动画的通常方法是编写一个在延迟后调用自身的动画方法(有关详细信息,请参见Method for having animated movement for canvas objects pythonTkinter, executing functions over time)。

你可以这样做:

^{pr2}$

相关问题 更多 >