Picture refresh instance for python Tkinter

  • 2021-06-28 13:11:43
  • OfStack

Call the GUI authoring library that comes with python

1 At first I wanted to make GUI with Tkinter. It is said on the Internet that python comes with it. Result input:


import tkinter

After that, display:


_ImportError: No module named tkinter_

I thought it was not installed, but I installed a bunch of things using the apt-get install command. It was found that it was useless to install them. () b

Later, you see that if you are using python2.7, you need to enter


import Tkinter

Then you can use it.

Display continuously refreshed pictures

Starting with TK's Label function to display pictures, you need to wait until mainloop () is called before displaying pictures, there is no way to refresh the image;Later, using Canvas, we found a way to display pictures without waiting for mainloop(), coded as follows:


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()

Later it was found that Label can also refresh pictures, the key is whether or not:


tk.updata()

The procedure for using Label is as follows, where.grid() is used to set the display location:


#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()

An attempt was made to place tk.Tk() inside the loop, but an error occurred when running to the second loop:


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

You need to replace tk.Tk with tk.Toplevel(), but two new panels appear for each loop.


Related articles: