社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

点击按钮跳过文件[tkinter+Python3.5]

Dr. Strange • 6 年前 • 1835 次点击  

假设我在一个目录中有'n'个图像文件 filedir 我想通过tkinter控制台查看。现在,我想在必要时跳过一些文件,使用调用函数的按钮单击事件 nextFile() .

import os


def nextFile():
    global img
    img_2 = process(img)
    return img_2


window = tk.Tk()
window.title("File Viewer")
files = os.listdir(filedir)
button1 = tk.Button(window, text="Browse Files...", fg="black", command=askopenfilename)
button2 = tk.Button(window, text="SELECT", width=50, command=nextFile)
canvas = tk.Canvas(window, width=width, height=height)
button1.pack(side=tk.LEFT)
button2.pack(side=tk.BOTTOM)
canvas.pack()

for f in files:
    img = cv2.cvtColor(cv2.imread(filedir + '/' + f), cv2.COLOR_BGR2RGB)
    photo = ImageTk.PhotoImage(image=Image.fromarray((img))
    canvas.create_image(0, 0, image=photo, anchor=tk.CENTER)

window.mainloop() 

如有任何帮助,我们将不胜感激。谢谢!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55597
文章 [ 1 ]  |  最新文章 6 年前
Mike - SMT
Reply   •   1 楼
Mike - SMT    6 年前

下面是一个简单的例子,使用PIL加载初始图像,然后使用按钮和函数加载每个下一个图像。

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

path = 'C:/your/file/path/here'

def nextFile():
    # the global is needed to keep track of current index and also keep
    # a reference of the image being displayed so its is not garbage collected.
    global current_ndex, image
    current_ndex += 1
    if current_ndex < len(files):
        img = Image.open('{}/{}'.format(path, files[current_ndex]))
        image = ImageTk.PhotoImage(img)
        # clear the canvas before adding the new image.
        canvas.delete("all")
        canvas.create_image(0, 0, image=image, anchor=tk.CENTER)


my_window = tk.Tk()
my_window.title("File Viewer")
files = os.listdir(path)

current_ndex = 0

button2 = tk.Button(my_window, text="Next", width=50, command=nextFile)
canvas = tk.Canvas(my_window, width=100, height=100)
button2.pack(side=tk.BOTTOM)
canvas.pack()

first_image = files[0]

img = Image.open('{}/{}'.format(path, first_image))
image = ImageTk.PhotoImage(img)
canvas.create_image(0, 0, image=image, anchor=tk.CENTER)
my_window.mainloop()