Python

【Python】Changing images periodically with tkinter

投稿日:

Overview

There is a good library in python to make GUI, that is tkinter. It can display images too. Here, we are trying to change images periodically with tkinter.

Python library to be used

Following three libraries are used.

  • tkinter

‘tkinter’ is used to make GUI.

  • PIL(pillow)

‘PIL’ is used to deal with images in the python.

  • threading

‘threading’ is used to change images automatically. Detail about that will be explained later.

By the way, if you are using anaconda which contains these three libraries already , you don’t have to install them with pip command.

Step1 : Display a image with tkintertkinter

At first, we are defining a function to show a image with tkinter.

# import libraries
import sys
import tkinter
from PIL import Image, ImageTk
import time

# Definition of a function to display image
def show_image():
  #Making instance of tkinter
    root = tkinter.Tk()
    root.title('test')
    root.geometry("400x300")

  # Opening image(Please change your actual path to your image)
    img = Image.open('yourimage.jpg')
    img = ImageTk.PhotoImage(img)

  # Definition of Canvas
    canvas = tkinter.Canvas(bg = "black", width=400, height=300)
    canvas.place(x=100, y=50)
    item = canvas.create_image(30, 30, image=img, anchor=tkinter.NW)

  # Display
    root.mainloop()

This function displays image by using canvas method of tkinter. ImageTK is necessary to use jpg file.

Step2 : Changing images

The purpose of here is changing some images automatically with using the function before we defined. But that function seems to have the problem that only some objects on GUI can control tkinter when it’s executing root.mainloop. To change images periodically and automatically without GUI objects, we ‘re using threading library like following.

import sys
import tkinter
from PIL import Image, ImageTk
import threading
import time

def show_image():
  
    # Definition as global to be controlled out of the function
    global item, canvas

    root = tkinter.Tk()
    root.title('test')
    root.geometry("400x300")
    img = Image.open('your_image.jpg')
    img = ImageTk.PhotoImage(img)
    canvas = tkinter.Canvas(bg = "black", width=400, height=300)
    canvas.place(x=100, y=50)
    item = canvas.create_image(30, 30, image=img, anchor=tkinter.NW)
    root.mainloop()

# make a thread and start to display a image
thread1 = threading.Thread(target=show_image)
thread1.start()

# Definition of a image to be changed
img2 = Image.open('your_image2.jpg')
img2 = ImageTk.PhotoImage(img2)
time.sleep(3) # cyclic 3 seconds

#Rewrite the item
canvas.itemconfig(item,image=img2)
time.sleep(3)

#Rewrite the item again
img = Image.open('your_image.jpg')
img = ImageTk.PhotoImage(img)
canvas.itemconfig(item,image=img)

This code can display a first image in thread and change it to second one after 3 seconds.

Summary

It may not the best way but it can realize what we want to do by using threading and rewrite the item out of the function.

-Python

執筆者:


comment

Your email address will not be published. Required fields are marked *

関連記事

【Python】Transforming datetime to date and time with pandas dateframe

Contents1 Original Data2 Transforming dataframe to date and time. Original Data This code is to make sample dataframe. import pandas as pd import datetime as dt df = pd.DataFrame([dt.datetime(2020,6,1,0,0,0),dt.datetime(2020,6,2,10,0,0),dt.datetime(2020,6,3,15,0,0)],columns=[’datetimes’])     datetimes 0 2020-06-01 00:00:00 1 2020-06-02 10:00:00 2 2020-06-03 15:00:00 Transforming dataframe to date and time. It can realize to use lambda & apply functions like following. df[’dates’] = df[’datetimes’].apply(lambda x : dt.date(x.year,x.month,x.day)) df[’times’] = df[’datetimes’].apply(lambda x : dt.time(x.hour,x.minute,x.second))      datetimes      dates   times 0 2020-06-01 00:00:00 2020-06-01 00:00:00 1 2020-06-02 10:00:00 2020-06-02 10:00:00 2 2020-06-03 15:00:00 2020-06-03 15:00:00 If you want to get with string, these code is better. df[’dates’] …

【Python】From DataFrame To list type

Contents1 Overview2 Example table in databse3 Solution Overview Pandas can get data from a database with read_sql easily.Here we can show how to convert dataframe to list type for only one row from database. Example table in databse a,b,c are columns of this test_table. abc110100220200330300440400test_table Let’s get only “a” column from this table with pandas.These are sample code. import pandas as pd import psycopg2 connection = psycopg2.connect(host=’host’, dbname=’database’, user=’username’, password=’password’) df = pd.read_sql("SELECT a FROM test_table", connection) df.head() Result If you want to convert this result from dataframe to list type, you may think like [1, 2, 3, 4]. There …

Bulk insert to Oracle with Python

Contents1 Overview2 Environments3 Step1 : Creating the table4 Step2 : Insert in bulk with executemany5 Summary Overview There is an example code to insert data in bulk to Oracle database with python cx_Oracle Environments python 3.7.3Oracle 18c Express Edition Step1 : Creating the table Creating the table ‘oracle_insert’ in the schema ‘USER01’. CREATE TABLE USER01.ORACLE_INSERT( col1 int ,col2 int ,col3 int ) Step2 : Insert in bulk with executemany dataset is the dataset to be insertedMaking a connection to database with cx_OracleInserting in bulk with using cur.executemany() import cx_Oracle dataset =[ [1,2,3] ,[4,5,6] ,[7,8,9] ,[10,11,12] ,[13,14,15] ,[16,17,18] ,[19,20,21] ] HOST …

Python : Insert dataframe data into MySQL table 

Contents1 Overview2 Environments3 Step1 : Making the table4 Step2 : Making data5 Step3 : Inserting data into MySQL table6 Additional explanation Overview Dataframe type in python is so useful to data processing and it’s possible to insert data as dataframe into MySQL . There is a sample of that. Environments Python 3.7.3MySQL 5.5.62 Step1 : Making the table Defining a table like the following. > CREATE DATABASE testdb; > CREATE TABLE testdb.mysql_table( col1 int ,col2 int ,col3 int ); Step2 : Making data Making data for insert from python. the data should be the same type as the table you …

【Python】Not getting all rows with BeautifulSoup

Contents1 Overview2 Environment3 Problem occurred example3.0.1 Result4 The way to fix it Overview When Scraping with Beautiful Soup a problem occurred like not getting all rows of the table but a few of them. This example shows how to fix it Environment Python 3.7.3 Problem occurred example This is a example table you want to scrape. NumberName1Sato2Kato3Ito4Goto I saw the html code in a web browser by pushing F12 key. <table class="test_table"> <thead> <tr> <th>Number</th> <th>Name</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Sato</td> </tr> </tbody> <tbody> <tr> <td>2</td> <td>Kato</td> </tr> </tbody> <tbody> <tr> <td>3</td> <td>Ito</td> </tr> </tbody> <tbody> <tr> <td>4</td> <td>Goto</td> …

Language Switcher

Categories