python Tkinter的图片刷新实例

yipeiwu_com6年前Python基础

调用python自带的GUI制作库

一开始想用Tkinter制作GUI的,网上说是python自带的,结果输入:

import tkinter

后,显示:

_ImportError: No module named tkinter_

以为是没有安装,还利用apt-get install 命令安装了一堆东西,安装完了发现还是没有用。(⊙﹏⊙)b

后来看到如果是用的python2.7的话,需要输入

import Tkinter

然后就可以用了。

显示连续刷新的图片

开始用的TK的Label功能来显示图片,需要等到调用mainloop()后才会显示图片,没找到可以刷新图像的方法;后来采用Canvas,才找到了可以不用等到mainloop()就可以显示图片的方法,代码如下:

from Tkinter import *
from PIL import Image, ImageTk
import time
import os
import cv2
num=0
tk=Tk()
canvas=Canvas(tk,width=500,height=500,bg = 'white')
while num<7:
 num +=1
 filename = str(num) + '.jpg'
 if os.path.isfile(filename):
 img1 = cv2.imread(filename)
 im1 = Image.fromarray(cv2.cvtColor(img1,cv2.COLOR_BGR2RGB)) 
 img = ImageTk.PhotoImage(image = im1)
 #img = ImageTk.PhotoImage(file = filename)
 itext = canvas.create_image((250,150),image = img)
 canvas.pack()
 tk.update()
 tk.after(1000)
tk.mainloop()

再后来发现用Label也可以实现图片的刷新,关键在于是否加了:

tk.updata()

使用Label的程序如下,其中的.grid()用于设置显示的位置:

#coding=utf-8
import Tkinter as tk
from PIL import Image, ImageTk
import cv2
import os
import time

def btnHelloClicked():
 labelHello.config(text = "Hello Tkinter!")

def resize(w,h,w_box,h_box,im):
 f1 = 1.0*w_box/w
 f2 = 1.0*h_box/h
 factor = min([f1, f2])
 width = int(w*factor)
 height = int(h*factor)
 return im.resize((width,height),Image.ANTIALIAS)

top = tk.Tk()
#-------------- image 1 --------------
for N in range(1,10):
 filename = str(N) + '.jpg'
 if os.path.isfile(filename):
 #top = tk.Toplevel()#tk.Tk()
 top.title("test the net.")
 #string
 labelHello = tk.Label(top,text = str(N),height = 5,width = 20,fg = "blue")
 labelHello.grid(row = 0,column = 1)
 img1 = cv2.imread(filename)
 im1 = Image.fromarray(cv2.cvtColor(img1,cv2.COLOR_BGR2RGB))
 #---resize the image to w_box*h_box
 w_box = 500
 h_box = 450
 w,h = im1.size
 im_resized1 = resize(w,h,w_box,h_box,im1)

 bm1 = ImageTk.PhotoImage(image = im_resized1)
 label1 = tk.Label(top,image = bm1,width = w_box,height = h_box)
 label1.grid(row = 1,column = 0)
 top.update()
 top.after(1000) 
top.mainloop()

其中尝试了将 tk.Tk()放在循环内部,但是运行到第二个循环的时候,会报错:

_tkinter.TclError: image "pyimage2" doesn't exist

需要将tk.Tk替换为tk.Toplevel(),但是每个循环都会新出现两个面板。

以上这篇python Tkinter的图片刷新实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python中shape计算矩阵的方法示例

本文实例讲述了Python中shape计算矩阵的方法。分享给大家供大家参考,具体如下: 看到机器学习算法时,注意到了shape计算矩阵的方法接下来就讲讲我的理解吧 >>&...

Python二叉树的遍历操作示例【前序遍历,中序遍历,后序遍历,层序遍历】

本文实例讲述了Python二叉树的遍历操作。分享给大家供大家参考,具体如下: # coding:utf-8 """ @ encoding: utf-8 @ author: lixia...

pycharm中使用anaconda部署python环境的方法步骤

pycharm中使用anaconda部署python环境的方法步骤

今天来说一下python中一个管理包很好用的工具anaconda,可以轻松实现python中各种包的管理。相信大家都会有这种体验,在pycharm也是有包自动搜索和下载的功能,这个我在前...

Python2和Python3中urllib库中urlencode的使用注意事项

前言 在Python中,我们通常使用urllib中的urlencode方法将字典编码,用于提交数据给url等操作,但是在Python2和Python3中urllib模块中所提供的urle...

Python工程师面试必备25条知识点

Python工程师面试必备25条Python知识点: 1.到底什么是Python?你可以在回答中与其他技术进行对比 下面是一些关键点: Python是一种解释型语言。这就是说,与C语言和...