首页 > 编程 > Python > 正文

python Tkinter的图片刷新实例

2019-11-25 12:45:18
字体:
来源:转载
供稿:网友

调用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, ImageTkimport timeimport osimport cv2num=0tk=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-8import Tkinter as tkfrom PIL import Image, ImageTkimport cv2import osimport timedef 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的图片刷新实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表