我使用tkinter
编写了一个小程序,根据参数我给出的程序生成一个数字(通过gui
接口)。我使用tkinter
直接使用Canvas
绘制了数字。现在我想生成一系列数字并将它们放在动画循环中。我可以生成gif
动画和load it into the figure,但问题是我是否可以直接在tkinter
中执行此操作。我可以将所有内容都放在循环中,但之后我将丢失事件处理程序。还有其他选择吗?
修改
这是一个简单的脚本:
#!/usr/bin/python
from Tkinter import *
import ttk
import numpy as np
colors = {1:'#F00',
2:'#0F0',
3:'#00F',
4:'#FF0',
5:'#0FF'}
root = Tk()
canvas = Canvas(root,width=400,height=400)
label = Label(root,text='seed')
values = StringVar()
combo = ttk.Combobox(root)
def painter(event):
seed = int(combo.get())
np.random.seed(seed)
nrows = 10
ncols = 10
Y = 0
dx = 400/nrows
dy = 400/ncols
for i in range(nrows):
X = 0
for j in range(ncols):
n = np.random.randint(1,5)
col = colors[n]
canvas.create_rectangle(X,Y,X+dx,Y+dy,width=1,fill=col)
X += dx
Y += dy
canvas.grid(column=0,row=0,rowspan=2)
combo.grid(row=1,column=1)
label.grid(row=0,column=1)
combo['values'] = [1,2,3,4]
combo.bind('<<ComboboxSelected>>',painter)
combo.current(0)
painter(None)
root.mainloop()
我可以更改painter
函数以包含无限循环但这样我永远不会到达mainloop()
,所以我只需要在创建主循环后调用它,但是如何?
答案 0 :(得分:1)
使用tkinter canvas的一些动画的简单示例:
import tkinter as tk
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title("Canvas animation example")
self.c = tk.Canvas(self, width=400, height=400)
self.c.pack()
self.f_index = 0 # index so we know which frame to draw next
# array to hold our frame data,
# you'll probably need this to hold more than
# just a set of coordinates to draw a line...
self.f_data = []
for num in range(0, 400, 5): # make up a set of fake data
self.f_data.append([num, num, num+10, num+10])
def next_frame(self):
data = self.f_data[self.f_index] # fetch frame data
self.c.delete('all') # clear canvas
self.c.create_line(*data) # draw new frame data
self.f_index += 1 # increment frame index
if (self.f_index >= len(self.f_data)): # check and wrap if at end of sequence
self.f_index = 0
self.c.after(50, self.next_frame) # call again after 50ms
if __name__ == "__main__":
app = App()
app.next_frame() # called manually once to start animation
# could be started with 'after' instead if desired
app.mainloop()
请注意,要删除的项目越多,重绘的速度就越慢。你需要有一些现实的期望,抽出一些10件物品就可以了,在一台不错的电脑上可以买到几百件,但1000件物品的表现会非常糟糕。