使用python中tkinter库显示图片点击按钮跳跳下一张图片

实现的主要功能:

        1、 显示图片

        2、 按钮按下,或者上下左右键切换 显示上一张图片,下一张图片

        3、 跳转按钮可以跳转到指定图片位置

        4、 对图片评价并保存到文本中

使用方法:

        在代码同级目录下新建一个png文件夹,将想要浏览的图片放入即可

        使用python中tkinter库显示图片点击按钮跳跳下一张图片_第1张图片

        软件界面:

         

 代码结构简单就很少注释了,仅供个人娱乐学习。

        直接给代码:

import datetime
import tkinter as tk
from PIL import Image, ImageTk
import  os

FilePath = 'png'
PngList = os.listdir(FilePath)

def Writediscuss(strdiscuss):
    f = open("discuss.txt",'a',encoding='utf8')
    strTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S  ')
    f.write(strTime + strdiscuss)
    f.close()

def resize(nX,nY):
    xNew = 640
    yNew = int(nY*640/nX)
    return (xNew,yNew)

root = tk.Tk()
root.geometry("1600x900")
root.title('')

img = Image.open('png\\T1 (1).jpeg')  # 打开图片
photo = ImageTk.PhotoImage(img)  #
imglabel = tk.Label(root, image=photo)
imglabel.place(x=0,y=0)

nIndex = 0 # 记录显示图片的文件下标

def submit():
    global nIndex
    enTextJumNum.delete(0.0, tk.END)
    enTextJumNum.insert(tk.INSERT, str(nIndex))

    enTextDiscuss.delete(0.0, tk.END)
    strDiscuss = PngList[nIndex].split('.')[0] +": "
    enTextDiscuss.insert(tk.INSERT, strDiscuss)

    print(PngList[nIndex])

    strPng = FilePath + '\\'+PngList[nIndex]

    global photo
    global imglabel
    photo = ImageTk.PhotoImage(file=strPng) # 打开图片看分辨率,如果太大则需要调整
    photoNew = Image.open(strPng).resize(resize(photo.width(),photo.height())) # 00调整图片的分辨率
    photo = ImageTk.PhotoImage(photoNew)
    imglabel.config(image=photo)
    nIndex = nIndex+1


def jumpTo():
    global nIndex
    nIndex = int(enTextJumNum.get('0.0', 'end'))
    print(nIndex)
    submit()

# 上一个
def pre():
    global nIndex
    nIndex = nIndex - 2
    print(nIndex)
    submit()

# 上一个
def home():
    global nIndex
    nIndex = 0
    print(nIndex)
    submit()

# 写入评论
def writeDiscuss():
    strDiscuss = enTextDiscuss.get('0.0', 'end')
    strDiscuss = PngList[nIndex] +": " + strDiscuss
    Writediscuss(strDiscuss)

def onEventNext(e):
    submit()

def onEventPre(e):
    pre()

# 输入控件
enTextJumNum = tk.Text(root)
enTextJumNum.place(x=400,y=800,height=20, width=58)
enTextJumNum.insert(tk.INSERT,'0')

# 跳转控件
btnjump = tk.Button(root, text="跳转", command=jumpTo)
btnjump.place(x=500,y=800)

# 下一张
btnNext = tk.Button(root, text="下一个", command=submit)
btnNext.place(x=280,y=800)

# 上一张
btnPre = tk.Button(root, text="上一个", command=pre)
btnPre.place(x=200,y=800)

# 首页
btnPre = tk.Button(root, text="首页", command=home)
btnPre.place(x=120,y=800)

# 输入评论控件
enTextDiscuss = tk.Text(root)
enTextDiscuss.place(x=800,y=600,height=200, width=300)
enTextDiscuss.insert(tk.INSERT,'评论')

# 评论写入文件
btnDiscuss = tk.Button(root, text="批语", command=writeDiscuss)
btnDiscuss.place(x=800,y=800)


root.bind("",onEventNext)
root.bind("",onEventNext)
root.bind("",onEventNext)

root.bind("",onEventPre)
root.bind("",onEventPre)
tk.mainloop()

你可能感兴趣的:(python,开发语言)